Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json add new object to existing json file C#

Tags:

json

c#

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 [].

like image 788
Joris van Roy Avatar asked Oct 12 '15 12:10

Joris van Roy


People also ask

How do I add an object to a JSON file?

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.

Can you Append to a JSON 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 a JSON file have multiple objects?

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.


1 Answers

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);
like image 148
Michael Mairegger Avatar answered Oct 23 '22 04:10

Michael Mairegger