【问题标题】:JSON get key path in nested dictionaryJSON获取嵌套字典中的关键路径
【发布时间】:2015-06-23 18:09:03
【问题描述】:
json = '{
    "app": {
        "Garden": {
            "Flowers": {
                "Red flower": "Rose",
                "White Flower": "Jasmine",
                "Yellow Flower": "Marigold"
            }
        },
        "Fruits": {
            "Yellow fruit": "Mango",
            "Green fruit": "Guava",
            "White Flower": "groovy"
        },
        "Trees": {
            "label": {
                "Yellow fruit": "Pumpkin",
                "White Flower": "Bogan"
            }
        }
    }'

这是我的 json 字符串,它经常变化,所以字典中的键位置每次都不相同,我需要 搜索一个键并打印它对应的值,因为每次我写了一个递归函数(见下文)来搜索时,json字符串都会改变 输入新的 json 字符串并打印值。但是现在的情况是我们多次使用相同的键和不同的值,怎么能 我得到了键的完整路径,这样更容易理解它是哪个键值,例如结果应该是这样的:

app.Garden.Flowers.white Flower = Jasmine
app.Fruits.White Flower = groovy
app.Trees.label.White Flower = Bogan

到目前为止我的代码:

import json
with open('data.json') as data_file:    
  j = json.load(data_file)

# j=json.loads(a)


def find(element, JSON):    
  if element in JSON:
    print JSON[element].encode('utf-8')
  for key in JSON:
    if isinstance(JSON[key], dict):
      find(element, JSON[key])



find(element to search,j)

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    您可以添加一个跟踪当前 JSON 路径的字符串参数。像下面这样的东西可以工作:

    def find(element, JSON, path, all_paths):    
      if element in JSON:
        path = path + element + ' = ' + JSON[element].encode('utf-8')
        print path
        all_paths.append(path)
      for key in JSON:
        if isinstance(JSON[key], dict):
          find(element, JSON[key],path + key + '.',all_paths)
    

    你可以这样称呼它:

    all_paths = []
    find(element_to_search,j,'',all_paths)
    

    【讨论】:

    • 谢谢……但是它是一个递归函数,最后返回 None ……我们可以修复它吗?
    • 从这样的函数返回多个东西会很棘手。一个更简单的方法是有一个你传入的列表,就像我在这个编辑版本中添加的那样,它收集了所有最终路径。调用该函数后,all_paths 将拥有打印的所有数据。
    • 第 7 行,在 find path = path + element + ' = ' + JSON[element].encode('utf8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3:序数不在范围内(128)
    • 那是一个单独的问题。如果您无法弄清楚出了什么问题,请使用您所知道的所有信息单独提出一个问题。
    • 单独发布了这个问题,无法调试为什么这个问题会在值中出现特殊字符的 bcoz。 stackoverflow.com/questions/31011731/…
    【解决方案2】:
    def getDictValueFromPath(listKeys, jsonData):
        """
        >>> mydict = {
            'a': {
                'b': {
                    'c': '1'
                }
            }
        }
        >>> mykeys = ['a', 'b']
        >>> getDictValueFromPath(mykeys, mydict)
        {'c': '1'}
        """
        localData = jsonData.copy()
        for k in listKeys:
            try:
                localData = localData[k]
            except:
                return None
    return localData
    

    gist

    【讨论】:

      【解决方案3】:

      这是 Brian 答案的修改版本,支持列表并返回结果:

      def find(element, JSON, path='', all_paths=None):
          all_paths = [] if all_paths is None else all_paths
          if isinstance(JSON, dict):
              for key, value in JSON.items():
                  find(element, value, '{}["{}"]'.format(path, key), all_paths)
          elif isinstance(JSON, list):
              for index, value in enumerate(JSON):
                  find(element, value, '{}[{}]'.format(path, index), all_paths)
          else:
              if JSON == element:
                  all_paths.append(path)
          return all_paths
      

      用法:

      find(JSON, element)
      

      【讨论】:

      • 它对我不起作用
      猜你喜欢
      • 1970-01-01
      • 2018-11-02
      • 2018-12-24
      • 2015-09-11
      • 2012-08-09
      • 2021-05-10
      • 1970-01-01
      • 2019-08-15
      • 2013-02-19
      相关资源
      最近更新 更多