Patthebug
Patthebug

Reputation: 4787

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. 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. 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. 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. I believe there has to be a pythonic way to do this.

How do I achieve this?

Upvotes: 1

Views: 10319

Answers (2)

newtover
newtover

Reputation: 32094

The format of the file you are trying to create is called JSON lines.

It seems, you are asking why the jsons are not separated with a newline. Because write method does not append the newline.

If you want implicit newlines you should better use print function:

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

Upvotes: 3

Håken Lid
Håken Lid

Reputation: 23064

Use the indent argument to output json with extra whitespace. 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

Upvotes: 0

Related Questions