I have a response from a post request:
JSON RESPONSE :
[ { “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? What I have now is:
JavaScript
x
7
1
all_C_Values= []
2
3
for entry in JSON_RESPONSE['c'].values()]
4
print("Adding element:")
5
print(element)
6
all_C_Values.append(element)
7
This doesn’t give me the answer I need though. Ideally the array would contain values [1,1].
If I loop through the response and try to append the value, I get:
TypeError: the JSON object must be str, bytes or bytearray, not list
Advertisement
Answer
You are getting that error because you cannot treat JSON as a dictionary yet, you must load it first
JavaScript
1
6
1
import json
2
3
response = json.loads(JSON_RESPONSE)
4
all_C_values = [dic['c'] for dic in response]
5
6