I have a JSON Lines format text file in which each line contains a valid JSON object. However,these JSON objects are not separated by a delimiter, so the file on a whole is not a valid JSON file. I want to add a comma after each JSON object, so as to make the the whole file a valid JSON file, which can be processed at once using json.load(). I have written the following code to add a comma at the end of each line:
import json
import csv
testdata = open('resutdata.csv', 'wb')
csvwriter = csv.writer(testdata)
with open('data.json') as f:
for line in f:
csvwriter.writerow([json.loads(line), ','])
testdata.close()
However, the csv file obtained adds a each line with quotes and a comma with quotes at the end. How do I solve my problem?
As you need to convert json lines
to json file
, you can directly convert it into json file
as follows:
import json
# Contains the output json file
resultfile = open('resultdata.json', 'wt')
data = []
with open('data.json') as f:
for line in f:
data.append(json.loads(line))
resultfile.write(json.dumps(data))
resultfile.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With