现在,我要为JSON文件中的每个值剥离所有空白和换行符
使用
pkgutil.simplegeneric()创建一个辅助函数
get_items():
import jsonimport sysfrom pkgutil import simplegeneric@simplegenericdef 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 arraydef 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 calldata = json.load(sys.stdin) # read json data from standard inputstrip_whitespace(data)json.dump(data, sys.stdout, indent=2)
注意:
functools.singledispatch()函数(Python
3.4+)将允许使用
collections‘
MutableMapping/MutableSequence代替
dict/list此处。
输出量
{ "anotherName": [ { "anArray": [ { "anotherKey": "value","key": "value" }, { "anotherKey": "value","key": "value" } ] } ], "name": [ { "someKey": "some Value" }, { "someKey": "another value" } ]}


