<p>正如我在<a href="https://stackoverflow.com/a/14055129/355230">other answer</a>中所说的,我认为没有一种方法可以在不遍历整个结构的情况下找到与<code>"P1"</code>键关联的所有值。然而,当我看到@Mike Brennan关于另一个JSON相关问题的<a href="https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json">How to get string objects instead of Unicode from JSON?</a>时,我想到了更好的方法</p>
<p>其基本思想是使用<code>object_hook</code>参数,而<code>json.loads()</code>只接受该参数来监视正在解码的内容并检查所需的值。<strong>注意:</strong>只有当表示是JSON <a href="http://json.org/" rel="nofollow noreferrer">^{<cd4>}</a>(即用大括号<code>{}</code>括起来的东西)时,这才起作用,就像在示例JSON中一样。</p>
<pre><code>import json
def find_values(id, json_repr):
results = []
def _decode_dict(a_dict):
try: results.append(a_dict[id])
except KeyError: pass
return a_dict
json.loads(json_repr, object_hook=_decode_dict) # Return value ignored.
return results
json_repr = '{"P1": "ss", "Id": 1234, "P2": {"P1": "cccc"}, "P3": [{"P1": "aaa"}]}'
print find_values('P1', json_repr)
</code></pre>
<p>输出:</p>
<pre class="lang-none prettyprint-override"><code>[u'cccc', u'aaa', u'ss']
</code></pre>