在新行上输出json对象组而不是单行

时间:2014-02-05 21:35:57

标签: python arrays json object newline

我正在加载一个json文件并尝试拉取一些值,然后逐行输出该组值。

当前输出如下:

{"time":"1:2:2","post":"1","user":"4","text":"Masaru Emoto"}{"time":"1:3:8","post":"8","user":"5","text":"Meteors"}{"time":"7:4:5","post":"1","user":"8","text":"Olympics"}

我希望它看起来像这样:

{"time":"1:2:2","post":"1","user":"4","text":"Masaru Emoto"}
{"time":"1:3:8","post":"8","user":"5","text":"Meteors"}
{"time":"7:4:5","post":"1","user":"8","text":"Olympics"}

我无法弄清楚在哪里添加“\ n”来修复输出。在此先感谢您的帮助。

代码:

import json

json_data = open('somefile.json', 'r+').read().decode("utf-8")
jdata = json.loads(json_data)

def id_generator(d):    

with open('formatted_file' + '.json', 'w') as outfile:
    for k, v in d.items():
        if isinstance(v, dict):
            id_generator(v)                    
        if isinstance(v, list):            
            for post in v:
                formated = {"time":post.get('created_time'),"user":post['from']['id'],
                               "post":post.get('id'),"text":post.get('description')}                                        
                out = json.dumps(formated, separators=(',', ':'))                                                         
                outfile.write(out)                                        
if __name__ == '__main__':
    try:
        id_generator(jdata)
    except TypeError:
        pass 

1 个答案:

答案 0 :(得分:7)

格式化打破了你的消息,但我假设你想在每次写电话(每个帖子)后想换行。

outfile.write(out + '\n')\n将在给定系统上自动转换为正确的行分隔符。