3 回答
TA贡献1818条经验 获得超11个赞
我最终做了一些快速而肮脏的事情
import json
with open('data.json') as jfile:
data = json.load(jfile)
for d in data:
print(json.dumps(d) + ',')
哪个打印
{'id': 200, 'name': 'bob', 'data': '<other> \n <xml> \n <data>'},
{"id": 200, "name": "bob", "data": "<other> \n <xml> \n <data>"},
刚刚将输出保存到另一个文件:P
结果失败了,因为文件太大了,但是嘿..已经很接近了!
TA贡献1936条经验 获得超6个赞
使用正则表达式
import re
html = '''
{
"id" : 10,
"name" : "bob",
"data" : "<some> \n <xml> \n <in here>"
},
{
"id" : 20,
"name" : "jane",
"data" : "<other> \n <xml> \n <in here>"
}
'''
def replaceReg(html, regex, new):
return re.sub(re.compile(regex), new, html)
html = replaceReg(html,' \n ',' ')
html = replaceReg(html,'{[\s]+','{ ')
html = replaceReg(html,'[\s]+}',' }')
html = replaceReg(html,',[\s]+',', ')
html = replaceReg(html,'}, ','\n')
print (html)
结果:
{ "id" : 10, "name" : "bob", "data" : "<some> <xml> <in here>"
{ "id" : 20, "name" : "jane", "data" : "<other> <xml> <in here>" }
TA贡献1836条经验 获得超4个赞
您只需要在写入另一个文件时替换结束换行符(\n ):
s=''
with open('input.txt','r') as f_in, open('output.txt', 'w') as f_out:
for line in f_in:
s += line.replace('\n', '')
f_out.write(s)
其中 input.txt 具有以下数据:
{
"id" : 10,
"name" : "bob",
"data" : "<some> \n <xml> \n <in here>"
},
{
"id" : 20,
"name" : "jane",
"data" : "<other> \n <xml> \n <in here>"
}
添加回答
举报