Appending a JSON item to a JSON list

Dhia Kennouche
Jan 25, 2019 · 1 min read

This post is more a question then an answer.

I started recently working on a Python project, I loved the language. But as a person coming from Java World, the uncertainty (I call it like this) in the use of variables and sometimes the ambiguity in its errors is killing me. Of course probably this is happening ‘cuz I’m still a newbie in this beautiful world.

Now to go to our point. I needed to open a file that contains a JSON List , and append a JSON object to it. I tried many ways to do this, my working solution (which looks so heavy also) is as the following :

→ Read the file as a json fileX list

→ Append our new item

→Dumps the list into string and store it inside again in the fileX

The actual code is as the following :

with open(‘file.json’, ‘r+’) as json_file:

a = json.load(json_file)

a.append(new_object)

with open(‘file.json’, ‘w+’) as json_file:

shhh = json.dumps(a)

json_file.write(shhh)

This solution works, but is so heavy as I said. I would be happy to see your optimizations for it.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store