我有一个JSON
文件具有以下结构:
{
"name":[
{
"someKey": "\n\n some Value "
},
{
"someKey": "another value "
}
],
"anotherName":[
{
"anArray": [
{
"key": " value\n\n",
"anotherKey": " value"
},
{
"key": " value\n",
"anotherKey": "value"
}
]
}
]
}
现在我想要strip
去掉每个值的所有空格和换行符JSON
文件。有没有某种方法可以迭代字典以及嵌套字典和列表的每个元素?
现在我想去掉 JSON 文件中每个值的所有空格和换行符
Using pkgutil.simplegeneric()
创建辅助函数get_items()
:
import json
import sys
from pkgutil import simplegeneric
@simplegeneric
def get_items(obj):
while False: # no items, a scalar object
yield None
@get_items.register(dict)
def _(obj):
return obj.items() # json object. Edit: iteritems() was removed in Python 3
@get_items.register(list)
def _(obj):
return enumerate(obj) # json array
def strip_whitespace(json_data):
for key, value in get_items(json_data):
if hasattr(value, 'strip'): # json string
json_data[key] = value.strip()
else:
strip_whitespace(value) # recursive call
data = json.load(sys.stdin) # read json data from standard input
strip_whitespace(data)
json.dump(data, sys.stdout, indent=2)
Note: functools.singledispatch() http://docs.python.org/3.4/library/functools#functools.singledispatch函数(Python 3.4+)将允许使用collections
' MutableMapping/MutableSequence http://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes代替dict/list
here.
Output http://ideone.com/Vfc6UW
{
"anotherName": [
{
"anArray": [
{
"anotherKey": "value",
"key": "value"
},
{
"anotherKey": "value",
"key": "value"
}
]
}
],
"name": [
{
"someKey": "some Value"
},
{
"someKey": "another value"
}
]
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)