Python JSON output new line

Viewed 33

Hello I am working on a ISS tracker using open notify api. However I want the JSON data being outputted onto a new line each time. My current code spits out the data all onto one line. Any good way of making the output usable? Thank you!

import requests
import json
import time
URL = "http://api.open-notify.org/iss-now.json"

filename = 'store.json'
#sending get request and saving the response as response object
i = 0
with open(filename, 'w') as file_object:
    #time for API calls
    while i<11:
        save = {}
        r = requests.get(url = URL)
        data = r.json()

        save['time'] = data['timestamp']
        save['latitude'] = data['iss_position']['latitude']
        save['longitude'] = data['iss_position']['longitude']
        json.dump(save, file_object)
        time.sleep(1)
        i+=1
1 Answers

You can use the indent keyword argument in order to have the json saved in a formatted state.

For example:

json.dump(save, file_object, indent=4)

from the python docs:

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

source

Related