简体   繁体   English

如何使用curl传递curl的JSON输出以使用python查询JSON值

[英]How to pipe JSON output of curl to query a JSON value using python

I am writing a bash script where the curl command returns a JSON array of objects and then I need to filter the required values out of those objects. 我正在编写一个bash脚本,其中curl命令返回对象的JSON数组,然后需要从这些对象中过滤出所需的值。 So I need to iterate through the objects to check then and parse them and finally get the result. 因此,我需要遍历对象以进行检查,然后解析它们并最终获得结果。

But inside my bash script if I do something like, 但是在我的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

I get the following error: 我收到以下错误:

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

Everything Ok if I remove the python part after the pipe, but why can't I use python in combination with curl ? 一切都好,如果我删除管道后的python部分,但为什么不能将python与curl结合使用? what am I doing wrong here ? 我在这里做错了什么?

In bash (and other shells), variables are not expanded when put inside single quotes. bash (和其他shell)中,变量放在单引号中时不会扩展。

Better approach than my original (as @chepner pointed out), pass the shell variable as command line argument to python command itself: 比我的原始方法更好的方法(如@chepner指出的),将shell变量作为命令行参数传递给python命令本身:

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

Original: 原版的:

You can get around by using double quotes like: 您可以使用双引号来解决:

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

ie terminating the single quote just before variable reference, and continuing afterwards. 即在变量引用之前终止单引号,然后再继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM