Reputation: 49
I have a JSON response - [{'address': '123 Any Street', 'province': 'ON', 'postal_code': 'L1P 2X2', 'co': 'BURL'}]
I would want to get individual values from this response like address = 123 Any Street, Province = ON etc in python. I want to use these values to be passed while rendering the template.
print(qry_activity)
if (qry_activity is not None):
results_activity = [{
"address": row.address,
"province": row.province,
"postal_code": row.postal_code,
"co": row.co
}
for row in qry_activity.all()]
How can I do this?
Upvotes: 0
Views: 165
Reputation: 1842
You could convert the input you're getting to a dictionary without the need to actually construct it by yourself using json.loads
or ast.literal_eval
:
If you want to use json.loads
you will need to fix the format, as using single quotes for the keys in JSON is invalid:
import json
json_response = "[{'address': '123 Any Street', 'province': 'ON', 'postal_code': 'L1P 2X2', 'co': 'BURL'}]"
json_response = json_response.replace('\'', '\"')
dictionary_result = json.loads(json_response)[0]
print(type(dictionary_result))
print(dictionary_result)
Which results in:
<class 'dict'>
[{'address': '123 Any Street', 'province': 'ON', 'postal_code': 'L1P 2X2', 'co': 'BURL'}]
Or use the ast.literal_eval
method which takes a string and literally evaluating it as is:
import ast
json_response = "[{'address': '123 Any Street', 'province': 'ON', 'postal_code': 'L1P 2X2', 'co': 'BURL'}]"
dictionary_result = ast.literal_eval(json_response)[0]
print(type(dictionary_result))
print(dictionary_result)
Which outputs the same as the first example.
If you're getting a list, and not a string that represents one, you could just retrieve the first element:
json_response = [{'address': '123 Any Street', 'province': 'ON', 'postal_code': 'L1P 2X2', 'co': 'BURL'}]
dictionary_result = json_response[0]
Upvotes: 1