我有一些 JSON 正在尝试使用 python 进行解析。问题是它是从 API 返回的,每次都会在返回的 JSON 中生成唯一的数字,这让我很难弄清楚如何解析。
下面是一个示例:返回的 JSON 中的所有内容都是统一的,除了一个对象(在本示例中为“258”)随每个结果而变化(即变为 35432、2848585 等)。
简而言之,我无法在代码中编写 data = json['data']['258']['name']
,因为“258”每次都会改变。
data
中总是有一项,因此我尝试了json['data'][0]['name']
,但没有成功。
有没有一种方法可以解析 JSON,其中存在一个正在更改的对象,因为它始终是 ['data']
中的唯一对象?也许有一些代码可以只在 JSON 结果中搜索 name:"matt"
?
{
data: {
258: {
name: "matt"
}
}
}
最佳答案
如果您确定“data”标记中只有一个对象,您可以执行以下操作:
import json
# Convert the JSON data into a Python dictionary
d = json.loads(json_data)
# Check if the data tag is present
if "data" in d:
# Loop through all the inner keys (in your case just the single integer key)
for key in d["data"]:
# Use the "key" variable in your path
print d["data"][key]["name"]
用于搜索结构:
def dict_search(key, value, p_dictionary):
""" Searches for a specific key, value combination within a multilevel python dictionary """
for k in p_dictionary:
if k == key and p_dictionary[k] == value:
print "Found %s, %s!" % (key, value)
return p_dictionary
# Check if inner dictionary is found
if type(p_dictionary[k]) is dict:
print "Using recursion to check the inner dictionary.."
dict_search(key, value, p_dictionary[k])
关于python - 解析随每个 API 查询而变化的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27370167/