I am trying to get JSON data from a localhost URL row by row and insert it into a JSON file. When I try to open the file, I receive an error that says Multiple JSON root elements
.
import urllib.parse
import urllib.request, json
import json
abc={}
for i in range(6666,6669):
print(i)
full_url="http://localhost/get/info" + str(i)
with urllib.request.urlopen(full_url) as url:
data = json.loads(url.read().decode())
print(data['id'])
abc={i:[data]}
with open('data.json', 'a') as outfile:
json.dump(abc,outfile)
A valid json object must have only one root
See How to read a JSON file containing multiple root elements?
You must append all json objects to an array and then write it to the json file
Resulting json object must be like
[
{ object 1 },
{ object 2 }
]
notice that there's only one root object in the json, the array containing all of the other objects