擅长:python、mysql、java
<p>我认为应该使用以下代码:</p>
<pre><code>def compareJson(example_json_s, target_json_s):
example_json = json.loads(example_json_s)
target_json = json.loads(target_json_s)
return compareParsedJson(example_json, target_json)
def compareParsedJson(example_json, target_json):
for x in example_json:
if type(example_json[x]) is not dict:
if not x in target_json or not example_json[x] == target_json[x]:
return False
else:
if x not in target_json or not compareParsedJson(example_json[x], target_json[x]):
return False
return True
</code></pre>
<p>在第一个函数中,我们解析完整的JSON对象(包括递归部分)。第二部分分析了它们。在</p>
<p>我对你的代码做了几处修改。在</p>
<ul>
<li>不需要先获取键的列表,您可以在<code>example_json.keys()</code>上迭代。另外,在您的示例中,我会将其替换为<code>keys.append(key)</code>。在</li>
<li>该函数检查嵌套json对象的类型现在是否为<code>dict</code>(它已经被解析)。如果不是,那么它会比较它们,如果是,那么它就进入下一个。您可能需要为列表添加一个类似的子句。在</li>
<li>当JSON的一部分不相同时,函数将立即返回<code>False</code>。在</li>
</ul>
<p>编辑:对于您发布的错误代码,我认为您可能没有正确解析json。我认为您的注释<code>#parsed_json</code>是指您已经完成了,但是我认为您错过了上面代码示例中包含的<code>json.loads</code>方法调用。。?在</p>