1

JSON is really new to me. How can i use JSON.NET to add a key value pair into a already created json file?

It looks like this:

{
"data": {
    "subData1": {
        "key1":"value1",
        "key2":"value2",
        "key3":"value3"
    },
    "subdata2": {
        "key4":"value4",
        "key5":"value5",
        "key6":"value6"
    }
}
"key7":"value7",
"key8":"value8"     
}

Say for an example that i want to change it to the following:

{
"data": {
    "subData1": {
        "key1":"value1",
        "key2":"value2",
        "key3":"value3"
    },
    "subdata2": {
        "key4":"value4",
        "key5":"value5",
        "key6":"value6"
    },
    "newSubData": {
        "myKey1":"myVal1",
        "myKey2":"myVal2",
        "myKey3":"myVal3"
    }
}
"key7":"anotherValChangeByMe",
"key8":"value8"     
}

Do i need to read the whole JSON file into a dynamic, and then change / add the things i need somehow ?

1
  • 1
    Deserialize the json to your model object. Add values to object and serialize it back to json and JSON.NET is the library that actually allows this to be done very easily. Commented Oct 14, 2014 at 22:23

2 Answers 2

3

You can parse the JSON into a JObject, manipulate it via the LINQ-to-JSON API, then get the updated JSON string from the JObject.

For example:

string json = @"
{
    ""data"": {
        ""subData1"": {
            ""key1"": ""value1"",
            ""key2"": ""value2"",
            ""key3"": ""value3""
        },
        ""subdata2"": {
            ""key4"": ""value4"",
            ""key5"": ""value5"",
            ""key6"": ""value6""
        }
    },
    ""key7"": ""value7"",
    ""key8"": ""value8""
}";

JObject root = JObject.Parse(json);
JObject data = (JObject)root["data"];
JObject newSubData = new JObject();
newSubData.Add("myKey1", "myValue1");
newSubData.Add("myKey2", "myValue2");
newSubData.Add("myKey3", "myValue3");
data.Add("newSubData", newSubData);
root["key7"] = "anotherValChangeByMe";

Console.WriteLine(root.ToString());

Output:

{
  "data": {
    "subData1": {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3"
    },
    "subdata2": {
      "key4": "value4",
      "key5": "value5",
      "key6": "value6"
    },
    "newSubData": {
      "myKey1": "myValue1",
      "myKey2": "myValue2",
      "myKey3": "myValue3"
    }
  },
  "key7": "anotherValChangeByMe",
  "key8": "value8"
}
Sign up to request clarification or add additional context in comments.

Comments

1

JSON is ultimately just a string. If you are working on the server side, then unless you want to try to parse out the JSON yourself, the easiest way is to use JSON.NET to deserialize it back into it's native object model. Of course, you can also do this on the client side with JSON.parse(), and add the value there, too.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.