Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of keys from Json.NET?

Tags:

c#

json.net

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);         }     } } 
like image 289
John Avatar asked Jun 29 '11 14:06

John


People also ask

What data type are the keys in JSON?

Keys must be strings, and values must be a valid JSON data type: string.

How can I tell if a JSON key is available?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().

Can JSON have multiple keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".

Can JSON have only keys?

The JSON format is deliberately based on a subset of JavaScript object literal syntax and array literal syntax, and JavaScript objects can only have strings as keys - thus JSON keys are strings too.


2 Answers

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

Documentation: JObject.Properties

like image 196
James Newton-King Avatar answered Sep 21 '22 20:09

James Newton-King


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

like image 40
Blairg23 Avatar answered Sep 22 '22 20:09

Blairg23