We help IT Professionals succeed at work.

Remove children property based on Parent  property from Json object using C#.net

1,464 Views
Last Modified: 2018-09-28
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
Comment
Watch Question

it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
No attached JSON.

-saige-

Author

Commented:
attached json string.
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
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-
Sr. Developer
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Chinmay PatelChief Technology Ninja
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
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_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
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-

Author

Commented:
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.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.