python - 解析随每个 API 查询而变化的 JSON 对象

标签 python json

我有一些 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/

相关文章:

python - python中包的全局变量可以被认为是邪恶的吗?

python - 元素树不加载 Google 地球导出的 KML

python - 为什么 os.path.isfile 返回 False?

python - "detail": "Method\"GET\"not allowed. 在 django 中调用端点

javascript - 在这种情况下如何处理数据驱动的输入?

python - 如何将数据插入 MySQL 数据库?

javascript - 如何从浏览器向 Node 脚本发送数据?

c - 如何在 C 中正确转义字符串中的字符以获得符合 JSON 的格式?

json - 带有证书的快速 REST 请求返回错误(代码 -999)

json - 即使不存在大文件,Git 错误 : large files "detected",