简体   繁体   English

如何从 JSON 格式中获取值

[英]How to get value from JSON format

I am using Python request module to get API response.我正在使用 Python 请求模块来获取 API 响应。 The response is should be JSON format.响应应该是 JSON 格式。 From the response how do I retrieve the specific value?从响应中如何检索特定值?

Example of API response: API 响应示例:

{
id: 2337975,
sha: "eac6910f89883110e673db27456b67f542df6d75",
ref: "mail-gun",
status: "manual",
created_at: "2021-03-01T09:15:02.409Z",
updated_at: "2021-03-01T09:19:14.983Z",
web_url: "https://gitlab.com/optimus/optimus-ci/-/pipelines/2337975"
}

From here I want retrieve on ID:2337975 assign into a variable in Python.从这里我想检索 ID:2337975 分配给 Python 中的变量。

Here is my code这是我的代码

url = f'https://gitlab.com/api/v4/projects/{pid}/pipelines?updated_after={update_after}&ref={branch}&status=manual'    
headers = {'Authorization' : 'Bearer xxxxxxxx'} 
response = requests.get(url, headers=headers)

output = json.loads(response.text)
print(output)

I can print the whole JSON format by print(output), but I only want to get a Id value.我可以通过打印(输出)打印整个 JSON 格式,但我只想得到一个 Id 值。

Anybody can help?有人可以帮忙吗?

change this:改变这个:

output = json.loads(response.text)

to this: (using json function you can receive the json response in string format) load the response into a python dictionary为此:(使用json function 您可以接收 json 响应字符串格式)将响应加载到python dictionary

response_json = json.loads(response.json())

and access the id key from response dictionary并从响应字典中访问id

variable = response_json["id"]

You should save this JSON code in a.json file, then you can open it, load it and then use variable ["id"].您应该将此 JSON 代码保存在 a.json 文件中,然后您可以打开它,加载它,然后使用变量 ["id"]。

parse the json and use the id as key in json to extract.解析 json 并使用 id 作为 json 中的键进行提取。

loaded_json = json.loads(json_data)
    for x in loaded_json:
        print("%s: %d" % (x, loaded_json[id]))

since the returned value of a json is an object (JavaScript Object Notation) you can treat it as such and just destructure the object with the [] notation as other pointed out response_json["id"] since the returned value of a json is an object (JavaScript Object Notation) you can treat it as such and just destructure the object with the [] notation as other pointed out response_json["id"]

I solve this using a naive way.我用一种天真的方式解决了这个问题。 which is convert the object to JSON > python list > python dictionary将 object 转换为 JSON > python 列表 > python 字典

response = requests.get(url, headers=headers, proxies=proxyDict)
response_list = response.json()
response_dict = response_list[0]
print(response_dict["id"])

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

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