我的.json文件中的数据采用以下格式
[
{
"FIRSTNAME":"NAOMI","EMAIL":"HJHU@hiuj.com","ADDLINE":"jnjn","CITY":"hbiu",
"FIRSTNAME":"gsf","EMAIL":"ghjujk@hn.com","ADDLINE":"kfjm","CITY":"hjhdjdyh",
"FIRSTNAME":"sgbg","EMAIL":"aeth@aeth.com","ADDLINE":"dzfht","CITY":"sbfbg",
"FIRSTNAME":"jkju","EMAIL":"ethe@th.com","ADDLINE":"tdhat","CITY":"dfhbdth",
}
]
我希望将CITY附加到ADDLINE,重命名为ADDRESS并在.csv文件中更新。 输出应为
[
{
"FIRST NAME":"NAOMI","EMAIL":"HJHU@hiuj.com","ADDRESS":"jnjn,hbiu",
"FIRST NAME":"gsf","EMAIL":"ghjujk@hn.com","ADDRESS":"kfjm,hjhdjdyh",
"FIRST NAME":"sgbg","EMAIL":"aeth@aeth.com","ADDRESS":"dzfht,sbfbg",
"FIRST NAME":"jkju","EMAIL":"ethe@th.com","ADDRESS":"tdhat,dfhbdth",
}
]
答案 0 :(得分:0)
在Python的主页上查看JSON库的文档:https://docs.python.org/2/library/json.html
您需要加载json文件:
data=json.loads(file('json.json').read())
然后处理数据:
for row in data:
row['ADDRESS'] = row['ADDRESS']+','+row['CITY']
del row['CITY']
...然后将其写回文件:
file('json2.json','w').write(json.dumps(data))
当然,在您的最终解决方案中,请务必关闭您已打开的文件。
顺便说一句,您的示例不是有效的JSON文件,并且您提供的输出看起来更像JSON而不是CSV,尽管它也不是有效的JSON。所以,我假设您希望输出为JSON。
如果您确实希望输出为CSV,请阅读https://docs.python.org/2/library/csv.html
答案 1 :(得分:0)
source_file = open('source.json', 'r')
output_file = open('output.csv', 'w')
for line in source_file:
item = json.loads(line.strip())
item['ADDRESS'] = "%s,%s" % (item['ADDRESS'], item['CITY'])
del item['CITY']
output_file.write(','.join(item.values()) + '\n')
source_file.close()
output_file.close()