learning...
learning...

Reputation: 3174

Searching and deleting a node from JSON

JSON is holding a data.

  1. I need to remove the node where the "id" value matches passed in value. In the below code var isRemoved = (dataDeserialized as JArray).Remove(index); is returning false. The node is not deleted. How can i delete the node?
  2. The property name "id" is even dynamic. It will get passed in. How can i check the property name along with value (current) to find the index?

Here is what i have so far:

var entityJson = @"
            [
              {
                'id': 1,
                'code': 'abc1'
              },
              {
                'id': 2,
                'code': 'abc2'
              }
            ]".Replace("'", "\"");

            var dataDeserialized = JsonConvert.DeserializeObject<dynamic>(entityJson);// DataLoader.DeserializeJson(entityJson, false);

            if(dataDeserialized.Count > 0)
            {
                var key = "id";
                var value = "2";
                var index = 0;
                var isFound = false;

                foreach(var d in dataDeserialized)
                {
                    if((string)d.id == value.ToString())
                    {
                        isFound = true;
                        break;
                    }
                    index++;
                }

                if (isFound)
                {
                    var isRemoved = (dataDeserialized as JArray).Remove(index);
                    if (isRemoved)
                    {
                        var setting = new JsonSerializerSettings
                        {
                            DateParseHandling = DateParseHandling.None,
                        };
                        var resul = JsonConvert.SerializeObject(dataDeserialized, setting);
                        //var result = JsonHelper.SerializeObject(dataDeserialized);
                    }
                }
            }

I have tried jObject as well but it is giving an error Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 2, position 13

dynamic obj = JObject.Parse(entityJson);
(obj.employees as JArray).RemoveAt(0);

Update #1: here is what worked for me for #1 above

if(dataDeserialized.Count > 0)
            {
                var key = "id";
                var value = "2";

                JArray list = new JArray();

                foreach (var d in dataDeserialized)
                {
                    if ((string)d.id != value.ToString())
                    {
                        list.Add(d);
                    }
                }

                if(list.Count > 0)
                {
                    var result = JsonConvert.SerializeObject(list);
                }
            }

Still, how can i do #2, checking the "key"?

Upvotes: 2

Views: 422

Answers (1)

Rafael Biz
Rafael Biz

Reputation: 463

If you don't want to deserialize this json to a strongly typed object, I would recommend working with the JObject and JArray classes from the Newtonsoft.Json package because they are much more flexible for this purpose.

So you can easily remove a node from the json with a dynamic key like this:

    string key = "id";
    int id = 2;

    var entityJson = @"
    [
        {
            ""id"": 1,
            ""code"": ""abc1""
        },
        {
            ""id"": 2,
            ""code"": ""abc2""
        },
        {
            ""id"": 3,
            ""code"": ""abc3""
        }
    ]";

    JArray jarray = JArray.Parse(entityJson);

    var item = jarray.Children().Where(i => (int)(i as JObject).GetValue(key) == id).SingleOrDefault();

    if (item != null)
    {
        jarray.Remove(item);
    }

    var resul = JsonConvert.SerializeObject(jarray);

Upvotes: 2

Related Questions