Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JSON.NET equivalent of XML's XPath, SelectNodes, SelectSingleNode?

Tags:

c#

json.net

At present, the structure of my code uses XmlDocument to load Xml data and then SelectNodes to iterate through a list of repeating items.

For each element, I am using XmlNode.SelectSingleNode to pick out the field elements.

I now want to use JSON.NET to achieve the same results with documents delivered to me as JSON. The answer can be something other than JSON.net, so long as it's C# integrable.

like image 481
Dead account Avatar asked Nov 08 '09 22:11

Dead account


People also ask

What is the equivalent of XPath for JSON?

JSONPath is a query language for JSON with features similar to XPath for XML. JSONPath is used for selecting and extracting a sub-section from the JSON document.

Can you use XPath for JSON?

XPath uses it to iterate over element collections and for predicates. In JavaScript and JSON it is the native array operator. Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.


2 Answers

Json.NET has SelectToken. It uses a syntax similar to DataBinder.Eval to get JSON via a string expression:

JObject o = JObject.Parse("{'People':[{'Name':'Jeff'},{'Name':'Joe'}]}");  // get name token of first person and convert to a string string name = (string)o.SelectToken("People[0].Name"); 

Or if you wanted to select multiple values:

JObject o = JObject.Parse("{'People':[{'Name':'Jeff','Roles':['Manager', 'Admin']}]}");  // get role array token of first person and convert to a list of strings IList<string> names = (string)o.SelectToken("People[0].Roles").Select(t => (string)t).ToList(); 

Documentation: Querying JSON with SelectToken

like image 73
James Newton-King Avatar answered Oct 13 '22 10:10

James Newton-King


Do you have an object hierarchy that you can map the the JSON? You could create an object tree (i.e. deserialize the JSON), and use LINQ's Where, SelectMany, etc.

like image 26
Marc Gravell Avatar answered Oct 13 '22 09:10

Marc Gravell