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:
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].
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
import json response = json.loads(JSON_RESPONSE) all_C_values = [dic['c'] for dic in response]