-2

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 Answers1

0

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

Alexander
  • 16,091
  • 5
  • 13
  • 29
  • The OP's problem isn't with indentation/human readability, but that all JSON outputs immediately follow after one another, rendering the final file unparsable. A simple line break between each JSON output would solve the problem like @jasonharper says, effectively making the output file in JSONL format. – blhsing Sep 23 '22 at 01:25