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

10,893

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)
Share:
10,893
Daisy.Hsu
Author by

Daisy.Hsu

Updated on June 13, 2022

Comments

  • Daisy.Hsu
    Daisy.Hsu almost 2 years

    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!