本文介绍了在新行而不是单行上输出json对象组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在加载json文件并尝试提取一些值,然后按行输出该组值.

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

当前输出如下:

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

我不知道在哪里添加"\ n"来修复输出.预先感谢您的帮助.

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

代码:

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

推荐答案

格式化有点破坏了您的信息,但是我认为您希望在每次写调用(每个帖子)后都换行.

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

只需执行outfile.write(out + '\n'). \n将自动转换为给定系统上的适当的行分隔符.

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

这篇关于在新行而不是单行上输出json对象组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:54