首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >新行而不是单行上的json对象的输出组

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

Stack Overflow用户
提问于 2014-02-05 21:35:56
回答 1查看 16.3K关注 0票数 4

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

当前的输出如下所示:

代码语言:javascript
复制
{"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"}

我想让它看起来像这样

代码语言:javascript
复制
{"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“来修复输出。提前谢谢你的帮助。

代码:

代码语言:javascript
复制
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 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-05 21:40:35

这种形式破坏了您的消息,但是我想您应该在每次写完后(每个帖子)之后换行。

只要做outfile.write(out + '\n')。在给定的系统上,\n将自动转换为适当的线路分隔符。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21589040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档