3 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
我最終做了一些快速而骯臟的事情
import json
with open('data.json') as jfile:
data = json.load(jfile)
for d in data:
print(json.dumps(d) + ',')
哪個(gè)打印
{'id': 200, 'name': 'bob', 'data': '<other> \n <xml> \n <data>'},
{"id": 200, "name": "bob", "data": "<other> \n <xml> \n <data>"},
剛剛將輸出保存到另一個(gè)文件:P
結(jié)果失敗了,因?yàn)槲募罅?,但是?.已經(jīng)很接近了!

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
使用正則表達(dá)式
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)
結(jié)果:
{ "id" : 10, "name" : "bob", "data" : "<some> <xml> <in here>"
{ "id" : 20, "name" : "jane", "data" : "<other> <xml> <in here>" }

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
您只需要在寫(xiě)入另一個(gè)文件時(shí)替換結(jié)束換行符(\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 具有以下數(shù)據(jù):
{
"id" : 10,
"name" : "bob",
"data" : "<some> \n <xml> \n <in here>"
},
{
"id" : 20,
"name" : "jane",
"data" : "<other> \n <xml> \n <in here>"
}
添加回答
舉報(bào)