将多个json对象写入json文件

时间:2017-07-03 19:38:46

标签: python json

我有一个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"
}

我想将其转换为json文件。这是我为此目的使用的代码:

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

但这给了我一个只有1行长数据的文件。我想在原始数据中为每个json对象添加一行。我知道还有一些其他StackOverflow问题试图解决有些类似的情况(通过外部插入' \ n'等),但由于某些原因它在我的情况下没有起作用。我相信必须有一种pythonic方法来做到这一点。

我如何实现这一目标?

2 个答案:

答案 0 :(得分:3)

您尝试创建的文件格式称为JSON lines

看来,你在问为什么jsons没有用换行符分隔。因为write方法不附加换行符。

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

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

答案 1 :(得分:0)

使用with open('filename.json', 'w') as outfile1: json.dump(data, outfile1, indent=4) 参数输出带有额外空格的json。默认设置是不输出换行符或额外空格。

${File}=    Get File  Path\\FileName.txt
@{list}=    Split to lines  ${File}     
:FOR    ${line} IN  @{list}
\   Log ${line}
\   ${Value}=   Get Variable Value  ${line}
\   Log ${Value}

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

相关问题