I'm trying to automate the adding of new objects to an existing json file. I looked all around the web but only found adding data and stuff but not an whole object. This is how the file that i wanna edit looks:
[
{"id":"123","name":"carl"}
]
and i want to go to
[
{"id":"123","name":"carl"},
{"id":"1234","name":"carl2"}
]
Thank you for all your answers but i don't think everyone is completely understanding what i mean i have tried some of the answers but then i get this:
[
"{\"id\":\"123\",\"name\":\"carl\"}"
]"{\"id\":\"1234\",\"name\":\"carl2\"}"
and i want everthing inbetween the [].
You need to load the file, then parse it using var val = JSON. parse(textFromFile) you can then use push to push it onto the end of that val val. push({/*new object*/}) , then you will need to stringify the val var newString = JSON. strigify(val) and then you finally can save newString to a file.
Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.
Can JSON have multiple objects? You can pass a single JSON object to create a single element, or a JSON array of group JSON objects to create multiple elements.
If you use json.NET you can simply deserialize and serialize the json.
var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);
list.Add(new Person(1234,"carl2");
var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);
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