[英]Parse JSON from CURL output using python
我正在尝试获取 id 的值,即“id”:59 ,它以 json 的形式出现在 curl 输出中。 下面是 json 中的 curl 输出:
[{"id":59,"description":"This is a demo project","name":"Demo_Project","name_with_namespace":"sam / Demo_Project","path":"demo_project","path_with_namespace":"sam/demo_project","created_at":"2020-03-02T08:43:13.664Z","default_branch":"master","tag_list":[],"ssh_url_to_repo":"ssh://git@od-test.od.com:2222/sam/demo_project.git","http_url_to_repo":"https://od-test.od.com/gitlab/sam/demo_project.git","web_url":"https://od-test.od.com/gitlab/sam/demo_project","readme_url":"https://od-test.od.com/gitlab/sam/demo_project/blob/master/README.md","avatar_url":null,"star_count":0,"forks_count":0,"last_activity_at":"2020-04-09T09:28:09.860Z","namespace":{"id":2259,"name":"sam","path":"sam","kind":"user","full_path":"sam","parent_id":null,"avatar_url":"https://secure.gravatar.com/avatar/755db8ssqaq50dcc9d189c53523b?s=80\u0026d=identicon","web_url":"https://od-test.od.com/gitlab/sam"}}]
我正在使用python来解析json并获取id的值。 我已尝试使用以下命令执行相同操作,但出现错误。
curl --header "PRIVATE-TOKEN: 9999ayayayar66" "https://od-test.od.com/gitlab/api/v4/search?scope=projects&search=demo_project" | python -c 'import sys, json; print(json.load(sys.stdin)["id"])'
错误:
谁能帮我正确的python命令来获取id的值。 提前致谢。
JSON 包含一组对象,但您将其视为单个对象:
import sys, json; print(json.load(sys.stdin)["id"])
您基本上是在说“这是一组对象,请给我对象的 ID” 。 这没有意义。
如果你假设你只想要数组中第一个对象的 ID,你可以使用这个:
import sys, json; print(json.load(sys.stdin)[0]["id"])
JSON 对象的根实际上是一个数组,因此您应该先从中取出第一项:
curl --header "PRIVATE-TOKEN: 9999ayayayar66" "https://od-test.od.com/gitlab/api/v4/search?scope=projects&search=demo_project" | python -c 'import sys, json; print(json.load(sys.stdin)[0]["id"])'
您必须编写print(json.load(sys.stdin)[0]["id"])
因为 json 响应是字典列表,而不是字典。
由于您还标记了Python Requests ,您的 CURL 命令可以转换为:
import requests
headers = {
'PRIVATE-TOKEN': '9999ayayayar66',
}
params = (
('scope', 'projects'),
('search', 'demo_project'),
)
response = requests.get('https://od-test.od.com/gitlab/api/v4/search', headers=headers, params=params)
然后您可以使用response.json()[0]["id"]
从JSON 响应内容中获取 id 值。 这使用内置的 JSON 解码器将 JSON 响应转换为字典列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.