代码之家  ›  专栏  ›  技术社区  ›  Ryan

如何通过命令行将json传递给python脚本?[副本]

  •  0
  • Ryan  · 技术社区  · 7 年前

    我想通过命令行上的json将一组简单的名称/值对传递给python脚本。

    $ curl -s https://jsonplaceholder.typicode.com/posts/1 | python3.6 -c 'import sys, json; print json.load(sys.stdin)'
      File "<string>", line 1
        import sys, json; print json.load(sys.stdin)
                                   ^
    SyntaxError: invalid syntax
    (23) Failed writing body
    

    json很简单:

    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat",
        "body": "quia et suscipit\nsuscipit..."
    }
    

    目标是分配如下变量:

    if json.load(sys.stdin)["title"] is not None:
        post_title = json.load(sys.stdin)["title"]
    

    我如何才能正确完成这一点?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Charles Duffy    7 年前

    您需要在参数周围加括号 print :

    python3.6 -c 'import sys, json; print(json.load(sys.stdin))'