Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new dictionary into existed json file with dictionary?

I have a json file saved in local server, such as:

    {
      "user": "user1",
      "id": "21779"
    } 

and I want to write another dict into this json file, I need new content like this:

    {
       {
         "user": "user1",
         "id": "21779"
       },
       {
         "user": "user2",
         "id": "21780"
       }
     }

Or:

     [
       {
         "user": "user1",
         "id": "21779"
       },
       {
         "user": "user2",
         "id": "21780"
       }
     ]

I try to use json.dump() to add the new element, but is displayed as:

    {
      "user": "user1",
      "id": "21779"
    }
    {
      "user": "user2",
      "id": "21780"
    }

It is not a valid json file.

How can I do use json.dump, json.load, or other methods? Thanks for help me!

like image 433
Daisy.Hsu Avatar asked Dec 18 '17 09:12

Daisy.Hsu


1 Answers

You have to read your JSON file and then convert it to list instead of dict. Then you just need to append to that list and overwrite your JSON file.

import json

data = json.load(open('data.json'))

# convert data to list if not
if type(data) is dict:
    data = [data]

# append new item to data lit
data.append({
  "user": "user2",
  "id": "21780"
})

# write list to file
with open('data.json', 'w') as outfile:
    json.dump(data, outfile)
like image 139
Vipin Kumar Avatar answered Nov 14 '22 23:11

Vipin Kumar