简体   繁体   English

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

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

I am getting a JSON file from a curl request and I want to read a specific value from it.我从 curl 请求中获得了 JSON 文件,我想从中读取特定值。 Suppose that I have a JSON file, like the following one.假设我有一个 JSON 文件,如下所示。 How can I insert the "result_count" value into a variable?如何将“result_count”值插入变量?

JSON 文件的示例

Currently, after getting the response from curl, I am writing the JSON objects into a txt file like this.目前,在得到 curl 的响应后,我正在将 JSON 对象写入这样的 txt 文件中。

json_response = connect_to_endpoint(url, headers)

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

Your json_response isn't a JSON content (JSON is a formatted string), but a python dict , you can access it using the keys您的json_response不是 JSON 内容(JSON 是格式化字符串),而是python dict ,您可以使用密钥访问它

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

Use the json module from the python standard library.使用 python 标准库中的json模块。
data itself is just a python dictionary, and can be accessed as such. data本身只是一个 python 字典,可以这样访问。

import json

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

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

you can parse a JSON string using json.loads() method in json module.您可以使用json.loads()模块中的json方法解析 JSON 字符串。

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

after that you can extract an element with specify element name in Brackets之后,您可以在括号中提取具有指定元素名称的元素

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

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

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