Link to home
Start Free TrialLog in
Avatar of victor s
victor s

asked on

Remove children property based on Parent property from Json object using

json string have parent and child and child has sub child(grand child). Here wanted to remove grand child. child name and grand child name is same so if i remove based on the name it will remove child and grand child.But I wanted to remove only GrandChild property. I have converted json string to JObject here my code snippet: i know this is wrong it deletes both child and grand child because names are same. Please find attached my Json object structure and json string. I am using Please let me know if you need any information.

JObject jObject = JObject.Parse(jsonString);
.Where(attr => attr.Name.Contains("NameofChild"))
.ForEach(attr => attr.Remove());
Avatar of it_saige
Flag of United States of America image

No attached JSON.

Avatar of victor s
victor s


attached json string.
Ok I think I understand what you are looking for, but, to clarify, can you give me a couple of example children/grandchildren that you want to remove.  Just browsing through the data, I did not find any childlren/grandchildren pairs which matched explicitly by name.

Avatar of Kelvin McDaniel
Kelvin McDaniel
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Bit of a hack, If this ChildProducts are always going to be a null value

How about removing it from the string itself? i.e.

jsonText.Replace("ChildProducts\": [],", string.Empty);
            JObject jObject = JObject.Parse(jsonText);

Open in new window

Otherwise, you can check if the ChildProducts has any children, if so do not remove it.
Looking at the data, I believe that the user only wants to remove certain grandchildren, not all, but I wanted clarification on this point.

solution given by Kelvin McDaniel is working perfectly for my requirements. I just modified a little bit removed inner foreach loop to get my desired result. appreciate your help.