簡體   English   中英

使用 python 獲取嵌套 json 中鍵值的通用方法

[英]Generic way to get the value of key in nested json using python

我是 python 的新手,我的要求是檢查 json 上是否存在給定的密鑰。 Json 不會一直相同。 所以,我正在尋找通用的 function 來檢查密鑰是否存在。 它適用於簡單的 json,但當 json 本身有另一個 json 且內部有一個 jsonarray 時,它不返回任何內容,如下所示:

{
  "id": "1888741f-173a-4366-9fa0-a156d8734972",
  "type": "events",
  "version": "1.0.0",
  "count": 3,
  "payload": {
    "cmevents": [
      {
        "exit_code": "0dbc2745-a964-4ce3-b7a0-bd5295afc620",
        "sourceEventType": "test01",
        "sourceType": "test",
        product:{
        "productCode":"101"
        }
      },
      {
        "exit_code": "1dbc2745-a964-4ce3-b7a0-bd5295afc620",
        "sourceEventType": "test02",
        "sourceType": "test",
        product:{
        "productCode":"102"
        }
      },
      {
        "exit_code": "2dbc2745-a964-4ce3-b7a0-bd5295afc620",
        "sourceEventType": "test03",
        "sourceType": "test",
        product:{
        "productCode":"103"
        }
      }
    ]
  }
}

從上面的 json 中,我想檢查 sourceEventType 鍵是否存在於 cmevents 列表的所有項目中。 以下是我用過的function

def checkElementsExist(element, JSON, path, whole_path):
    if element in JSON:
        path = path + element + ' = ' + JSON[element].encode('utf-8')
        whole_path.append(path)
        //
    for key in JSON:
        if isinstance(JSON[key], dict):
            finds(element, JSON[key], path + key + '.', whole_path)

撥打 function:

whole_path = []
finds('sourceEventType', json, '', whole_path)

誰能幫我找到正確的解決方案

遞歸 function 在這里可能是一種更簡單的方法。

  1. 使用json.loads(text)解析 json
  2. 搜索樹
import json
text = json.loads(".....")
def search_for_key(key, content) -> bool:
    # Search each item of the list
    # if found return true
    if isinstance(content, list):
        for elem in content:
            if search_for_key(key, elem):
                return True
    # Search each key of the dictionary for match
    # If the key isn't a match try searching the value
    # of the key in the dictionary
    elif isinstance(content, dict):
        for key_in_json in content:
            if key_in_json == key:
                return True
            if search_for_key(key, content[key_in_json]):
                return True
    # If here it's a number or string. There is no where else to go
    # return false
    else:
        return False
print(search_for_key("some_key?", text))

絕對有可能使您的路徑方法起作用,但是您確實需要使用堆棧/隊列跟蹤您尚未探索的路徑(並且您可以通過遞歸函數免費獲得它)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM