我正在比较一个 json 对象的所有元素是否都在另一个 json 中。 为此,我抓取小一层中的所有 key ,并检查它们是否在大一层中以及它们是否相同。为了进入更深的层,我调用该函数,为其提供包含更深层的元素。 (在这个函数中,现在我用关键“结果”检测更深的层,但我 future 它将更改为可变键。 我的问题是我无法调用递归函数。当尝试在函数中调用该函数时,它在脚本中表示“字符串索引必须是整数,而不是 unicode”。
def compareJson(example_json_s, target_json_s):
#parsed_json
example_json = example_json_s
target_json = target_json_s
p = 0
keys = []
for key in example_json.keys():
keys.insert(p, key)
p = p + 1
passed = 0;
for x in keys:
print "Keys"
if x != "results":
if not x in target_json or x not in example_json.keys() and not example_json[x] == target_json[x]:
passed = 1
else:
print """###inhabits "results " going one layer deeper"""
compareJson(example_json[key], target_json[key])
return passed
和一些示例 json 对象:
{
"results": {
"clock": true,
"update": false,
"autoreg": false
}
}
{
"id": "1523",
"dlid": "009029",
"serial": "1017030022",
"statuscode": 128,
"results": {
"event": true,
"counter": true,
"clock": true,
"eqep": true,
"usb": false,
"modem": true,
"sim": true,
"pin": true,
"encrypt": false,
"upload": true,
"update": true,
"autoreg": true
},
"ok": false,
"confirmed": false
}
这里的错误代码:
Traceback (most recent call last):
File "/home/philip/Desktop/empfang_test.py", line 199, in <module>
empfange() #Programm wartet in einer Endlosschleife auf eingehende Nachrichten.
File "/home/philip/Desktop/empfang_test.py", line 193, in empfange
checkvalue=compareJson(json.loads(config[1][1]),parsed_json_dummy)
File "/home/philip/Desktop/empfang_test.py", line 183, in compareJson
compareJson(example_json[key],target_json[key])
TypeError: string indices must be integers, not str
最佳答案
这是我的解决方案
def contained(a, b):
""" checks if dictionary a is fully contained in b """
if not isinstance(a, dict):
return a == b
else:
return all(contained(v, b.get(k)) for k, v in a.items())
print(contained(d1, d2))
对于您的输入,给出 False
,对于
d1 = {
"results": {
"clock": True,
"update": True,
"autoreg": True
}
}
给出True
和
d1 = {
"results": {
"clock": True,
"update": True,
"autoreg": True,
"qqq": True
}
}
即目标中缺少一个键(例如 qqq
),它给出 False
当然你可以这样调用
contained(json.loads(example_json_s), json.loads(target_json_s))
从 JSON 字符串开始时
关于python - json与python中另一个json的递归比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34762634/