Skip to main content
 首页 » 编程设计

python之在 JSON 中搜索变量然后返回父标签的名称

2024年11月24日17artech

所以我正在尝试获取一个标签的名称,该标签是一个标签的父级,该标签包含我在循环中早些时候定义的搜索变量。父标签总是不同的。 这是我正在使用的 json 的结构。

{ 
  "Data" : { 
    "Site" : { 
      "RandomID I don't want" : { 
        "Service" : { 
          "RandomID I want" : "Namers" 
        }, 
        "title" : "(The string im searching for)" 
      } 

等等等等......

所以我试着缩小我的结果

firebase = urlopen('firebase.json').read().decode('utf-8') 
aniIndex = json.loads(firebase) 
aniIndex2 = aniIndex.get("Data") 
aniIndex3 = aniIndex2.get("Site") 
print(aniIndex3) #Returns the section I want to search into 

现在我的问题是如何搜索标签,因为下一个标签是随机名称。所以我想我是否可以搜索“Title”的文本并检查它的父标签。我试图找到一种方法来做到这一点,但没有一种方法真正适用于我遇到的情况

编辑:我弄乱了 Json 结构,已修复(很抱歉现在是凌晨 5 点)

请您参考如下方法:

这里有一些代码似乎可以满足您的需求。如果您需要所有带有 title 标记的项目,则排除 break 语句并在循环内对您想要的项目执行一些操作。

data = { 
    "Data": { 
        "Site": { 
            "RandomID I don't want": { 
                "Service": { 
                    "RandomID I want": "Namers" 
                }, 
                "title": "(The string im searching for)" 
            } 
        } 
    } 
} 
 
for v in data["Data"]["Site"].values(): 
    if "title" in v: 
        if v["title"] == "(The string im searching for)": 
            id_i_want = list(v["Service"].keys())[0] 
            break 
 
print("Id I want: '{}'".format(id_i_want)) 

输出:

Id I want: 'RandomID I want'