[英]How to get values from all instances of key in JSON in Python
I have a response from a post request:我有一个帖子请求的回复:
JSON RESPONSE: JSON 回复:
[ { "a": 3, "b": 2, "c": 1, }, { "a": 3, "b": 2, "c": 1 } ] [{“a”:3,“b”:2,“c”:1,},{“a”:3,“b”:2,“c”:1}]
How would I get the value from all instances of "c" and add it to an array?我如何从“c”的所有实例中获取值并将其添加到数组中? What I have now is:我现在拥有的是:
all_C_Values= []
for entry in JSON_RESPONSE['c'].values()]
print("Adding element:")
print(element)
all_C_Values.append(element)
This doesn't give me the answer I need though.这并没有给我我需要的答案。 Ideally the array would contain values [1,1].理想情况下,数组将包含值 [1,1]。
If I loop through the response and try to append the value, I get:如果我遍历响应并尝试 append 值,我得到:
TypeError: the JSON object must be str, bytes or bytearray, not list TypeError: JSON object must be str, bytes or bytearray, not list
Try this:尝试这个:
D = [ { "a": 3, "b": 2, "c": 1, }, { "a": 3, "b": 2, "c": 1 } ]
x = [x['c'] for x in D]
print(x)
You are getting that error because you cannot treat JSON as a dictionary yet, you must load it first您收到该错误是因为您还不能将 JSON 视为字典,您必须先加载它
import json
response = json.loads(JSON_RESPONSE)
all_C_values = [dic['c'] for dic in response]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.