Code-47
Code-47

Reputation: 423

Add a JToken to a specific JsonPath in a JObject

I have a JObject that looks like this..

{
    "address": [
        {
            "addressLine1": "123",
            "addressLine2": "124"
        },
        {
            "addressLine1": "123",
            "addressLine2": "144"
        }
    ]
}

for JsonPath address[2], I want to add the following JObject to the address array.

{
     "addressLine1": "123",
     "addressLine2": "144"
}

I want to do something like json.TryAdd(jsonPath, value);

If there was an object at index 2 i would have easily done

var token = json.SelectToken(jsonPath);
if (token != null && token .Type != JTokenType.Null)
{
      token .Replace(value);
}

but since that index does not exist I'll get null as the value of token

Upvotes: 0

Views: 1101

Answers (1)

Selim Yildiz
Selim Yildiz

Reputation: 5370

As we mentioned on comment section, you can not add/replace item to index if index does not exist. In that case you need to add item as a new member of JArray instead, or you can use Insert to add item at the specified index :

JObject value = new JObject();
value.Add("addressLine1", "123");
value.Add("addressLine2", "144");

JObject o = JObject.Parse(json);
int index = 2;
JToken token = o.SelectToken("address[" + index + "]");
if (token != null && token.Type != JTokenType.Null)
{
    token.Replace(value);
}
else //If index does not exist than add to Array
{
    JArray jsonArray = (JArray)o["address"];
    jsonArray.Add(value);
    //jsonArray.Insert(index, value); Or you can use Insert

}

Upvotes: 1

Related Questions