<p>这可能不是最有效的过程,但它是有效的。我将该示例复制到名为<code>json.txt</code>的文件中,然后读取它,用<code>json.loads()</code>反序列化它,并使用一对函数递归地清理它及其内部的所有内容。</p>
<pre><code>import json
def clean_dict(d):
for key, value in d.iteritems():
if isinstance(value, list):
clean_list(value)
elif isinstance(value, dict):
clean_dict(value)
else:
newvalue = value.strip()
d[key] = newvalue
def clean_list(l):
for index, item in enumerate(l):
if isinstance(item, dict):
clean_dict(item)
elif isinstance(item, list):
clean_list(item)
else:
l[index] = item.strip()
# Read the file and send it to the dict cleaner
with open("json.txt") as f:
data = json.load(f)
print "before..."
print data, "\n"
clean_dict(data)
print "after..."
print data
</code></pre>
<p>结果。。。</p>
<pre><code>before...
{u'anotherName': [{u'anArray': [{u'anotherKey': u' value', u'key': u' value\n\n'}, {u'anotherKey': u'value', u'key': u' value\n'}]}], u'name': [{u'someKey': u'\n\n some Value '}, {u'someKey': u'another value '}]}
after...
{u'anotherName': [{u'anArray': [{u'anotherKey': u'value', u'key': u'value'}, {u'anotherKey': u'value', u'key': u'value'}]}], u'name': [{u'someKey': u'some Value'}, {u'someKey': u'another value'}]}
</code></pre>