如何在path中返回父级,并在JSON中定位键

2024-04-26 11:13:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出如何找到一个名为['text']的键,然后从嵌套中获取父键。这是第三个不同的键,所有其他的标签都是一样的。你知道吗

    html_data = data['data']['document_data']['dataItem-ihmty5rw']['text']

我用这个函数来获取钥匙:

    def printKeysValues(d):
      for k, v in d.items():
        if isinstance(v, dict):
            printKeysValues(v)
        else:
          print("{0} : {1}".format(k, v))

此函数用于查找缩进:

   def pretty(d, indent=0):
     for key, value in d.items():
        print('\t' * indent + str(key))
        if isinstance(value, dict):
            pretty(value, indent+1)
        else:
            print('\t' * (indent+1) + str(value))

Tags: 函数textinfordataifvaluedef
1条回答
网友
1楼 · 发布于 2024-04-26 11:13:27

我仍然不能完全确定这是否是您想要的,但是如果您只是想要每个项目的文本字典,我认为这应该起作用:

# a dictionary of item string to dictionary containing a "text" key
item_map = data['data']['document_data']  

for item_string, item_map in item_map.iteritems():
    print item_string  # the item string (e.g. 'dataItem-ihmty5rw')
    print item_map['text']  # this is the text associated with the item string

相关问题 更多 >