Ricky Collins
Ricky Collins

Reputation: 31

Insert new element in nested json object

I have nested JSON like this with some nested levels:

{
  "Main": [
    {
      "id": 123,
      "Sub1": [
        {
          "id": 2345,
          "description": "...",
          "Sub11": [
            {
              "subid": 6633,
              "xid": 5555
            }
          ]
        }
      ]
    },
    {
      "id": 332,
      "Sub1": [
        {
          "xid": 5555,
          "description": "...",
          "Sub11": [
            {
              "subid": 6794
            },
            {
              "subid": 4444
            }
          ]
        }
      ]
    }
  ]
}

This is just a example. I need to traverse through whole JSON and insert some json object (NewNode) for the element with property xid: 5555

Ex. Before-

"Sub11": [
        {
          "subid": 6633,
          "xid": 5555
        }
      ]

After-

"Sub11": [
        {
          "subid": 6633,
          "xid": 5555,
          "NewNode":{
             "SomeProperty": "value"
          }
        }
      ]

I'm thinking to traverse through each node, check for the property name (xid). If it's value matches, then insert node (NewNode) there.

Is there easier way to achieve this?

Upvotes: 1

Views: 3860

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129807

You can use Json.Net's LINQ-to-JSON API to do this pretty easily:

var root = JObject.Parse(json);
var matches = root.DescendantsAndSelf()
                  .OfType<JObject>()
                  .Where(x => x["xid"] != null && x["xid"].ToString() == "5555");

foreach (JObject jo in matches)
{
    jo.Add("NewNode", new JObject(new JProperty("SomeProperty", "value")));
}

Console.WriteLine(root.ToString());

Fiddle: https://dotnetfiddle.net/DzJd3K

Upvotes: 2

Related Questions