84

I'm using C# and Json.NET. If I have a JObject, I want a list of the keys within the object, similar to how object.Keys() returns the keys within the object. This seems like it'd be obvious, but I'm having a rough time finding a way to do this.

Edit: I'm traversing through the object, and I want to spit out all the keys in the object as I go through. I realize that this example will result in seeing the same key multiple times, and that's OK for my needs.

public void SomeMethod(JObject parent) {
    foreach (JObject child in parent.Children()) {
        if (child.HasValues) {
        //
        // Code to get the keys here
        //
        SomeMethod(child);
        }
    }
}
Noctis
  • 11,507
  • 3
  • 43
  • 82
John
  • 3,430
  • 2
  • 31
  • 44
  • Could you give a code example which you're using? Anyway try smth like this JArray sizes = (JArray)jObject["Keys"]; – sll Jun 29 '11 at 14:30
  • 1
    Unfortunately that was not successful. `object["Keys"]` returns the value of the key with the name "Keys" – John Jun 29 '11 at 20:40

2 Answers2

160
IList<string> keys = parent.Properties().Select(p => p.Name).ToList();

Documentation: JObject.Properties

James Newton-King
  • 48,174
  • 24
  • 109
  • 130
  • Has this been remove as of 5.0.8 version? Because I can't no longer get the Keys for a JObject. – aminjam Nov 05 '13 at 14:12
  • @bigaj Nope, it has not...just tested this exact code on 5.0.8 and it appears to work fine for me – Robert Petz Nov 09 '13 at 07:21
  • 3
    @Big AJ: did you import System.Linq? It's required to do the Select() query and won't be available without it. – Wolfgang Schreurs Dec 01 '13 at 13:54
  • 2
    throws: error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. – ljgww Feb 21 '18 at 14:50
  • Great use case for LINQ. The more I use LINQ the more I like it (when it's appropriate). – db2 Apr 03 '19 at 16:03
29

From Converting a JSON.NET JObject's Properties/Tokens into Dictionary Keys

You can simply convert the JObject into a Dictionary object and access the method Keys() from the Dictionary object.

Like this:

using Newtonsoft.Json.Linq;
//jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, string> dictObj = jsonObj.ToObject<Dictionary<string, string>>();

You can now access those keys via the dictObj.Keys() method. You can see if a key exists by performing dictObj.ContainsKey(keyName) also.

Obviously, you can format the Dictionary however you want (could be Dictionary<string, object>, etc.).

Community
  • 1
  • 1
Blairg23
  • 11,334
  • 6
  • 72
  • 72