检查 json 中一个键的值是否有另一个键

Check if value of one key in json has another key

我正在尝试打印我的 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'

如何遍历它?所以我可以对每个单独的键和值进行一些处理?

递归示例:

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 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