Avatar of victor s
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("NameofChild"))
.ToList()
.ForEach(attr => attr.Remove());
json-string.txt
jsonStructure.jpg
.NET ProgrammingC#LINQ QueryJSON

Avatar of undefined
Last Comment
victor s

8/22/2022 - Mon
it_saige

No attached JSON.

-saige-
victor s

ASKER
attached json string.
it_saige

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-
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
Kelvin McDaniel

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Chinmay Patel

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.
it_saige

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-
victor s

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.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.