简体   繁体   English

如何从 python 中的 JSON 字符串中提取单个值而不将其解析为 Javascript object

[英]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'}]我有一个 JSON 回复 - [{'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.我想从这个响应中获取单独的值,例如 python 中的 address = 123 Any Street, Province = ON 等。我想在呈现模板时使用这些值来传递。

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 :您可以将获得的输入转换为字典,而无需使用json.loadsast.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:如果你想使用json.loads你需要修复格式,因为在 JSON 中使用单引号是无效的:


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:或者使用ast.literal_eval方法,该方法接受一个字符串并按字面意思对其进行评估:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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