简体   繁体   English

将多个json对象写入一个json文件

[英]Writing multiple json objects to a json file

I have a list of json objects that I would like to write to a json file. 我有一个要写入json文件的json对象列表。 Example of my data is as follows: 我的数据示例如下:

    {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
    "_id": "abc",
} {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
}

I would like to wirte this to a json file. 我想将其写入json文件。 Here's the code that I am using for this purpose: 这是我用于此目的的代码:

with open("filename", 'w') as outfile1:
    for row in data:
        outfile1.write(json.dumps(row))

But this gives me a file with only 1 long row of data. 但这给了我一个只有一长行数据的文件。 I would like to have a row for each json object in my original data. 我想在原始数据中为每个json对象设置一行。 I know there are some other StackOverflow questions that are trying to address somewhat similar situation (by externally inserting '\\n' etc.), but it hasn't worked in my case for some reason. 我知道还有其他一些StackOverflow问题正在尝试解决一些类似的情况(通过在外部插入'\\ n'等),但是由于某种原因,它在我的情况下不起作用。 I believe there has to be a pythonic way to do this. 我相信必须有一种Python的方式来做到这一点。

How do I achieve this? 我该如何实现?

The format of the file you are trying to create is called JSON lines . 您尝试创建的文件格式称为JSON行

It seems, you are asking why the jsons are not separated with a newline. 看来,您是在问为什么json不能用换行符分隔。 Because write method does not append the newline. 因为write方法不会追加换行符。

If you want implicit newlines you should better use print function: 如果需要隐式换行符,则最好使用print功能:

with open("filename", 'w') as outfile1:
    for row in data:
       print(json.dumps(row), file=outfile1)

Use the indent argument to output json with extra whitespace. 使用indent参数可输出带有额外空白的json。 The default is to not output linebreaks or extra spaces. 默认为不输出换行符或多余的空格。

with open('filename.json', 'w') as outfile1:
     json.dump(data, outfile1, indent=4)

https://docs.python.org/3/library/json.html#basic-usage https://docs.python.org/3/library/json.html#basic-usage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM