Home > Mobile >  How can I add a new object to a list of objects in a .json file?
How can I add a new object to a list of objects in a .json file?

Time:08-11

I have a myfile.json file:

{
 "entries":
   [{"name": "my_name",
     "id":"my_id",
     "url" : "myurl"
    }
  ]
}

I would like it to look like this:

   {
     "entries":
       [{"name": "my_name",
         "id":"my_id",
         "url" : "myurl"
        },
        {"name": "my_name2",
         "id":"my_id2",
         "url" : "myurl2"
        }
      ]
    }

Assuming I have the values my_name2, my_id2 and myurl2 already stored in strings, what is the best course of action ?

CodePudding user response:

Read the whole file, parse it as JSON into a variable, add the new member to the Array, then serialize it again to JSON, and overwrite the original file.

  • Related