victor s
asked on
Remove children property based on Parent property from Json object using C#.net
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 C#.net. Please let me know if you need any information.
JObject jObject = JObject.Parse(jsonString);
jObject.Descendants()
.OfType<jproperty>()
.Where(attr => attr.Name.Contains("Nameof Child"))
.ToList()
.ForEach(attr => attr.Remove());
json-string.txt
jsonStructure.jpg
JObject jObject = JObject.Parse(jsonString);
jObject.Descendants()
.OfType<jproperty>()
.Where(attr => attr.Name.Contains("Nameof
.ToList()
.ForEach(attr => attr.Remove());
json-string.txt
jsonStructure.jpg
ASKER
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.
-saige-
-saige-
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
Otherwise, you can check if the ChildProducts has any children, if so do not remove it.
How about removing it from the string itself? i.e.
jsonText.Replace("ChildProducts\": [],", string.Empty);
JObject jObject = JObject.Parse(jsonText);
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.
-saige-
-saige-
ASKER
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.
-saige-