繁体   English   中英

使用 Python 从 json 文件中读取特定值

[英]Read a specific value from a json file with Python

我从 curl 请求中获得了 JSON 文件,我想从中读取特定值。 假设我有一个 JSON 文件,如下所示。 如何将“result_count”值插入变量?

JSON 文件的示例

目前,在得到 curl 的响应后,我正在将 JSON 对象写入这样的 txt 文件中。

json_response = connect_to_endpoint(url, headers)

f.write(json.dumps(json_response, indent=4, sort_keys=True))

您的json_response不是 JSON 内容(JSON 是格式化字符串),而是python dict ,您可以使用密钥访问它

res_count = json_response['meta']['result_count']

使用 python 标准库中的json模块。
data本身只是一个 python 字典,可以这样访问。

import json

with open('path/to/file/filename.json') as f:
  data = json.load(f)

result_count = data['meta']['result_count']

您可以使用json.loads()模块中的json方法解析 JSON 字符串。

response = connect_to_endpoint(url, headers)
json_response = json.load(response)

之后,您可以在括号中提取具有指定元素名称的元素

result_count = ['meta']['result_count']

暂无
暂无

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

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