【问题标题】:Check if value of one key in json has another key检查json中一个键的值是否有另一个键
【发布时间】:2018-04-12 18:13:30
【问题描述】:

我正在尝试打印我的 json 内容。我知道如何只打印键和值,但我也想访问键中的对象。这是我的代码:

json_mini = json.loads('{"one" : {"testing" : 39, "this": 17}, "two" : "2", "three" : "3"}')
for index, value in json_mini.items():
    print index, value
    if value.items():
        for ind2, val2 in value.items():
            print ind2, val2

这给了我这个错误:AttributeError: 'unicode' object has no attribute 'items'

如何迭代它?所以我可以对每个单独的键和值做一些处理吗?

【问题讨论】:

  • 您可以查看if isinstance(value, dict)。当value"2" 时,您希望value.items() 返回什么?
  • 你需要一个递归函数,因为你的 JSON 是多级的
  • @AleksandrBorisov 你能提供 Python 2.7 的解决方案吗?
  • 这个问题有什么问题所以我投了反对票?
  • @khelwood 您的解决方案有效!

标签: python json python-2.x


【解决方案1】:

递归示例:

import json


def func(data):
    for index, value in data.items():
        print index, value
        if isinstance(value, dict):
            func(value)


json_mini = json.loads('{"one" : {"testing" : 39, "this": 17}, "two" : "2", "three" : "3"}')
func(json_mini)

【讨论】:

  • 谢谢,我希望你的回答也能对其他人有所帮助,因为在堆栈溢出中只有 Python 3 的解决方案
【解决方案2】:

这是一种适用于 Python 2 和 3 的递归方式,它不使用 isinstance()。相反,它使用异常来确定给定元素是否是子对象。

import json

def func(obj, name=''):
    try:
        for key, value in obj.items():
            func(value, key)
    except AttributeError:
        print('{}: {}'.format(name, obj))

json_mini = json.loads('''{
                              "three": "3",
                              "two": "2",
                              "one": {
                                  "this": 17,
                                  "testing": 39
                              }
                          }''')

func(json_mini)

输出:

this: 17
testing: 39
three: 3
two: 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多