如何使用Python在JSON树中搜索特定级别

时间:2017-10-08 12:13:26

标签: python json

我正在尝试在特定级别的JSON树中学习搜索方法。我有以下JSON模板示例:

"Pair": {
    "Instrument_A": {
        "Segment A": {
            "default": {
                "value X": 1,
                "value Z": 2,
                "value Y": 3,

            }
        },
        "Segment B": {
            "default": {
                "value X": 1,
                "value Z": 2,
                "value Y": 3,

            }
        }
    },
    "Instrument_B": {
        "Segment A": {
            "not-default": {
                "value X": 1,
                "value Z": 2,
                "value Y": 3,

            }
        }
    }
}   

我的目标是计算名称不等于" 默认"的所有数组,例如,您可以在工具B,Segment下的4级看到A,有一个名为" not-default "

的对象

2 个答案:

答案 0 :(得分:0)

您可以使用json包解析json并遍历字典。

Python2:

import json
json_str = "..."
json_object = json.loads(json_str)
for pair_k, pair_v in json_object.iteritems():
    for inst_k, inst_v in pair_v.iteritems():
        for seg_k, seg_v in inst_v.iteritems():
            if not seg_v == "default"
                pass # do whatever you want - print, append to list, etc. 

Python3:

import json
json_str = "..."
json_object = json.loads(json_str)
for pair_k, pair_v in json_object.items():
    for inst_k, inst_v in pair_v.items():
        for seg_k, seg_v in inst_v.items():
            if not seg_v == "default"
                pass # do whatever you want - print, append to list, etc. 

答案 1 :(得分:0)

count = Counter()

def count_keys(data):
    if isinstance(data, dict):
        for key, value in data.items():
            if key != 'default':
                count[key]+=1
            count_keys(data[key])

count_keys(data)
print(count)

打印

Counter({'value X': 3, 'value Z': 3, 'value Y': 3, 'Segment A': 2, 'Pair': 1,'Instrument_A': 1, 'Segment B': 1, 'Instrument_B': 1, 'not-default': 1})