Python 3.从json中提取数据

时间:2022-05-26 10:35:53

How to extract 41677?

如何提取41677?

My json:

我的json:

{"41677":{"key":"ilya","premium":"true"}}

My code:

我的代码:

params={"id": "ilya", "fmt": "json"}
r=requests.get("somesite", params=params )
data=json.loads(r.text)

3 个解决方案

#1


2  

By using loads, your JSON string will be converted to a dictionary which maps keys to values.

通过使用加载,您的JSON字符串将转换为将键映射到值的字典。

Since you need the key 41677, you can simply call data.keys()[0] to retrieve the first key of your dictionary.

由于您需要密钥41677,您只需调用data.keys()[0]即可检索字典的第一个密钥。

EDIT:

编辑:

Also, if you have a list of that JSON structure, you can iterate over the keys and values using the items function, like so:

此外,如果您有一个JSON结构的列表,您可以使用items函数迭代键和值,如下所示:

for key, value in data.items():
    print key  # 41677
    print value  # {"key":"ilya","premium":"true"}

#2


0  

By using Requests' built-in json attribute:

通过使用Requests的内置json属性:

data = requests.get("somesite", params=params ).json().keys()[0]

assuming the json it returns is {"41677":{"key":"ilya","premium":"true"}}:

假设它返回的json是{“41677”:{“key”:“ilya”,“premium”:“true”}}:

>>>print data
"41677"

#3


0  

import json
s = {"41677":{"key":"ilya","premium":"true"}}
d = json.dumps(s)
l = json.loads(d)
l.keys()

#1


2  

By using loads, your JSON string will be converted to a dictionary which maps keys to values.

通过使用加载,您的JSON字符串将转换为将键映射到值的字典。

Since you need the key 41677, you can simply call data.keys()[0] to retrieve the first key of your dictionary.

由于您需要密钥41677,您只需调用data.keys()[0]即可检索字典的第一个密钥。

EDIT:

编辑:

Also, if you have a list of that JSON structure, you can iterate over the keys and values using the items function, like so:

此外,如果您有一个JSON结构的列表,您可以使用items函数迭代键和值,如下所示:

for key, value in data.items():
    print key  # 41677
    print value  # {"key":"ilya","premium":"true"}

#2


0  

By using Requests' built-in json attribute:

通过使用Requests的内置json属性:

data = requests.get("somesite", params=params ).json().keys()[0]

assuming the json it returns is {"41677":{"key":"ilya","premium":"true"}}:

假设它返回的json是{“41677”:{“key”:“ilya”,“premium”:“true”}}:

>>>print data
"41677"

#3


0  

import json
s = {"41677":{"key":"ilya","premium":"true"}}
d = json.dumps(s)
l = json.loads(d)
l.keys()