简体   繁体   中英

how can I extract single values from a JSON string in python without parsing it to Javascript object

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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