如何在json文件中获取key的值数据

2024-09-28 19:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个来自url的json文件,我想在json中得到key'OnePie_key'的值

    import requests
    hosturl = requests.get(url='http://api.jsoneditoronline.org/v1/docs/abf48114b71a43f380cd114d37a4bb9d')
    print(hosturl.json(['OnePie_KEY']))

但它不起作用

我的Json来自URL

{"name":"Kisame","schema":{"type":"NONE","url":null,"id":null,"content":null,"leftPanel":false,"rightPanel":false},"updated":"2021-09-19T16:47:45.419Z","_rev":33,"_id":"abf48114b71a43f380cd114d37a4bb9d","data":"{\n  \"HWID\": {\n    \"000001\": [\n      \"Riici\",\n      \"xx399\",\n      \"\",\n      1\n    ]\n  },\n  \"OnePie_KEY\": \"112233445566778899\",\n  \"MD5\": \"121321312514654665\"\n}"}

我想阅读键“OnePie_key”中的值,非常感谢您的帮助


Tags: 文件keyimportidjsonfalsehttpurl
1条回答
网友
1楼 · 发布于 2024-09-28 19:28:22

代码的前两行工作正常:

import requests
hosturl = requests.get(url='http://api.jsoneditoronline.org/v1/docs/abf48114b71a43f380cd114d37a4bb9d')

您的hosturl变量现在包含许多有用的信息

print(hosturl)
# Prints "<Response [200]>" telling us the request was successful

print(hosturl.text)
# Renders the body of the response as text: '{"name":"Kisame","schema":{"t...

还有.json()方法,它将.text属性读取为JSON,实际上是将其转换为Python dict和list

json_response = hosturl.json()

print(json_response.keys())
# Prints the following keys:
# dict_keys(['name', 'schema', 'updated', '_rev', '_id', 'data'])

检查['data']键,我们可以看到它的内容仍然是一个字符串,而不是一个对象

print(json_response['data'])
# '{\n  "HWID": {\n    "000001": [\n      "Riici",\n      "xx399",\n      "",\n      1\n    ]\n  },\n  "OnePie_KEY": "112233445566778899",\n  "MD5": "121321312514654665"\n}'

我们在json模块中使用loads()(加载字符串)方法来转换此字符串:

import json

data = json.loads(json_response['data'])

print(data)
# {'HWID': {'000001': ['Riici', 'xx399', '', 1]}, 'OnePie_KEY': '112233445566778899', 'MD5': '121321312514654665'}
# Notice no newline characters or quotes around the {}    

print(data.keys())
# dict_keys(['HWID', 'OnePie_KEY', 'MD5'])

print(data['OnePie_KEY'])
# 112233445566778899

相关问题 更多 >