Joh*_*est 13 python json strip
我有一个JSON具有以下结构的文件:
{
"name":[
{
"someKey": "\n\n some Value "
},
{
"someKey": "another value "
}
],
"anotherName":[
{
"anArray": [
{
"key": " value\n\n",
"anotherKey": " value"
},
{
"key": " value\n",
"anotherKey": "value"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
现在我想要strip删除JSON文件中每个值的所有空格和换行符.有没有办法迭代字典的每个元素和嵌套的字典和列表?
现在我想剥离JSON文件中每个值的所有空格和换行符
使用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)
Run Code Online (Sandbox Code Playgroud)
注意: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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
使用JSON解析文件:
import json
file = file.replace('\n', '') # do your cleanup here
data = json.loads(file)
Run Code Online (Sandbox Code Playgroud)
然后遍历生成的数据结构。
| 归档时间: |
|
| 查看次数: |
20387 次 |
| 最近记录: |