I am loading a json file and trying to pull some values then output that group of values by line.
The current output looks like this:
{"time":"1:2:2","post":"1","user":"4","text":"Masaru Emoto"}{"time":"1:3:8","post":"8","user":"5","text":"Meteors"}{"time":"7:4:5","post":"1","user":"8","text":"Olympics"}
And I want it to look like this:
{"time":"1:2:2","post":"1","user":"4","text":"Masaru Emoto"}
{"time":"1:3:8","post":"8","user":"5","text":"Meteors"}
{"time":"7:4:5","post":"1","user":"8","text":"Olympics"}
I can't figure out where to add the "\n" to fix the output. Thanks in advance for the help.
Code:
import json
json_data = open('somefile.json', 'r+').read().decode("utf-8")
jdata = json.loads(json_data)
def id_generator(d):
with open('formatted_file' + '.json', 'w') as outfile:
for k, v in d.items():
if isinstance(v, dict):
id_generator(v)
if isinstance(v, list):
for post in v:
formated = {"time":post.get('created_time'),"user":post['from']['id'],
"post":post.get('id'),"text":post.get('description')}
out = json.dumps(formated, separators=(',', ':'))
outfile.write(out)
if __name__ == '__main__':
try:
id_generator(jdata)
except TypeError:
pass
The formating kinda broke your message, but I assume you want to newline after each write call (each post).
Just do outfile.write(out + '\n')
. The \n
will be automagically converted to proper line separator on given system.
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