0

I am trying to get the sub key\values of a key's value. What I am trying to accomplish is to remove the elements that are empty or have "-" or have "N/A". I can not seem to figure out out to iterate over the values to search.

{
  "name": {
    "first": "Robert",
    "middle": "",
    "last": "Smith"
  },
  "age": 25,
  "DOB": "-",
  "hobbies": [
    "running",
    "coding",
    "-"
  ],
  "education": {
    "highschool": "N/A",
    "college": "Yale"
  }
}

Code:

JObject jObject = JObject.Parse(response);

foreach (var obj in jObject)
{
    Console.WriteLine(obj.Key);
    Console.WriteLine(obj.Value);
}

I am trying to search "first":"Robert","middle":"","last":"Smith"

2 Answers 2

2

You can use Descendants method to get child tokens of type JProperty, then filter their values and print them or remove one by one

var properties = json.Descendants()
    .OfType<JProperty>()
    .Where(p =>
    {
        if (p.Value.Type != JTokenType.String)
            return false;

        var value = p.Value.Value<string>();
        return string.IsNullOrEmpty(value);
    })
    .ToList();

    foreach (var property in properties) 
        property.Remove();

    Console.WriteLine(json);

Gives you the following result (with "middle": "" property removed)

{
  "name": {
    "first": "Robert",
    "last": "Smith"
  },
  "age": 25,
  "DOB": "-",
  "hobbies": [
    "running",
    "coding",
    "-"
  ],
  "education": {
    "highschool": "N/A",
    "college": "Yale"
  }
}

You can also add more conditions to return statement, like return string.IsNullOrEmpty(value) || value.Equals("-"); to remove "DOB": "-" property as well

Sign up to request clarification or add additional context in comments.

2 Comments

The next question is how to loop over the result you have and remove the element that has a value of "" such as "middle"?
@FirstElement just call property.Remove(), but materialize the result to list to avoid enumeration was changed exception, I've updated an answer
1

You can recursively iterate JObject properties:

    private static void IterateProps(JObject o)
    {
        foreach (var prop in o.Properties())
        {
            Console.WriteLine(prop.Name);
            if (prop.Value is JObject)
            {
                IterateProps((JObject)prop.Value);
            }
            else
            {
                Console.WriteLine(prop.Value);
            }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.