Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing properties from complex json object

Tags:

json

c#

json.net

I am trying to remove some properties which are dynamic input from JObject(converted json to JObject). i can do this on parent elements but not the nested child elements. INPUT

 {
  "id": 1,
  "name": "something",
  "marks": [
    {
      "pid": 1000,
      "sub": "AAA",
      "rank": 2
    },
    {
      "pid": 1001,
      "sub": "BBB",
      "rank": 10
    }
  ]
}

Now i wand to remove the id from parent and pid from each marks property in json. This list is dynamic and may grow in future. data is above provided is an example but the original list(marks in example) contains more than 20 properties.

CODE TRIED (which is deleting only id property from the parent)

string[] props = new string[] { "id", "pid" };
JObject jObject = JsonConvert.DeserializeObject<JObject>(str.ToLower());
if (jObject != null)
{
    jObject.Properties()
           .Where(attr => props.Contains(attr.Name))
           .ToList()
           .ForEach(attr => attr.Remove());
}
like image 503
user3625533 Avatar asked May 08 '26 11:05

user3625533


1 Answers

You can create a function and call it recursively if the nested values are JObject or JArray, like the following code:

1 - Create the main function RemoveIds:

public static void RemoveIds(JObject jObject, string[] props)
{
    List<JProperty> jProperties = jObject.Properties().ToList();

    for (int i = 0; i < jProperties.Count; i++)
    {
        JProperty jProperty = jProperties[i];
        if (jProperty.Value.Type == JTokenType.Array)
        {
            RemoveFromArray((JArray)jProperty.Value, props);
        }
        else if (jProperty.Value.Type == JTokenType.Object)
        {
            RemoveIds((JObject)jProperty.Value, props);
        }
        else if (props.Contains(jProperty.Name))
        {
            jProperty.Remove();
        }
    }
}

2 - Create simple method RemoveFromArray that call the main function inside a loop:

private static void RemoveFromArray(JArray jArray, string[] props)
{
    foreach(JObject jObject in jArray)
    {
        RemoveIds(jObject, props);
    }
}

3 - Call main function in the code like :

JObject jObject = JsonConvert.DeserializeObject<JObject>(json.ToLower());
if (jObject != null)
{
    RemoveIds(jObject, new string[] { "id", "pid" });

    Console.WriteLine(jObject);
}

4 - Result:

{
  "name": "something",
  "marks": [
    {
      "sub": "aaa",
      "rank": 2
    },
    {
      "sub": "bbb",
      "rank": 10
    }
  ]
}

I hope you find this helpful.

like image 80
Mohammed Sajid Avatar answered May 11 '26 01:05

Mohammed Sajid