将多个json对象写入json fi

2024-10-01 07:37:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要写入json文件的json对象的列表。我的数据示例如下:

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

我想把这个wirte到一个json文件中。以下是我用于此目的的代码:

^{pr2}$

但这给了我一个只有1长行数据的文件。我希望为原始数据中的每个json对象设置一行。我知道还有一些其他StackOverflow问题试图解决类似的情况(通过外部插入'\n'等),但由于某些原因,它在我的案例中没有起作用。我相信一定有一种Python式的方法。在

我如何实现这一点?在


Tags: 文件数据对象idjsonfalsedatebucket
2条回答

您试图创建的文件的格式称为JSON lines。在

看起来,你在问为什么json没有用换行符分开。因为write方法不追加换行符。在

如果需要隐式换行符,最好使用print函数:

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

使用indent参数输出带有额外空白的json。默认情况下不输出换行符或额外空格。在

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

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

相关问题 更多 >