output group of json objects on new line instead of single line

这一生的挚爱 提交于 2019-12-23 12:00:16

问题


I am loading a json file and trying to pull some values then output that group of values by line.

The current output looks like this:

{"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"}

And I want it to look like this:

{"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"}

I can't figure out where to add the "\n" to fix the output. Thanks in advance for the help.

Code:

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:


The formating kinda broke your message, but I assume you want to newline after each write call (each post).

Just do outfile.write(out + '\n'). The \n will be automagically converted to proper line separator on given system.



来源:https://stackoverflow.com/questions/21589040/output-group-of-json-objects-on-new-line-instead-of-single-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!