python 保存json去掉空格_如何从JSON文件的每个值中删除空白和换行符?

Now I want to strip off all he whitespaces and newlines for every value in the JSON file

使用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)

注意:^{}函数(Python 3.4+)允许在这里使用collections'^{},而不是dict/list。{

"anotherName": [

{

"anArray": [

{

"anotherKey": "value",

"key": "value"

},

{

"anotherKey": "value",

"key": "value"

}

]

}

],

"name": [

{

"someKey": "some Value"

},

{

"someKey": "another value"

}

]

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值