簡體   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