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

如何使用python管道curl的JSON输出来查询JSON值

  •  0
  • LearnUntillDeath  · 技术社区  · 6 年前

    我正在编写一个bash脚本,其中curl命令返回一个JSON对象数组,然后我需要从这些对象中筛选出所需的值。所以我需要遍历对象,然后检查并解析它们,最后得到结果。

    但在我的bash脚本中,如果我执行以下操作,

    for i in 1 2 3 4
        do
            curl -XGET 'https://gitlab.com/user/api/v4/projects/1/pipelines/1/jobs' | python -c 'import sys, json; print(json.load(sys.stdin)[$i]["stage"])'
        done
    

    我得到以下错误:

    File "<string>", line 1
        import sys, json; print($i)
                                ^
    SyntaxError: invalid syntax
    100  3016  100  3016    0     0  18748      0 --:--:-- --:--:-- --:--:-- 19210
    (23) Failed writing body
    

    如果在管道之后删除python部分,一切都可以,但是为什么不能将python与curl结合使用呢?我做错了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   heemayl    6 年前

    在里面 bash (和其他shell)中,变量放在单引号内时不会展开。

    比我原来的方法更好的方法(正如@chepner指出的),将shell变量作为命令行参数传递给 python 命令本身:

    curl ... | python -c \
       'import sys, json; print(json.load(sys.stdin)[sys.argv[1]]["stage"])' "$i"
    

    原件:

    您可以使用双引号,如:

    curl ... | python -c \
                'import sys, json; print(json.load(sys.stdin)['"$i"']["stage"])'
    

    i、 e.在变量引用之前终止单引号,然后继续。