Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using JSONPath with SelectToken to query for JSONPath expressions in your C# application


If you use Newonsoft's Json.NET for the .NET environment, you can use its SelectToken implementation to make JSONPath queries of JSON documents. First, you'll parse the JSON into JObject and then make a query.

Getting ready

You'll need to include the Json.NET assembly in your application. To do this, follow the steps in Chapter 7, Using JSON in a Type-safe Manner, in the Getting ready section of the How to Deserialize an object with Json.NET recipe.

How to do it…

Here's how to extract all titles of all books from the example in the introduction and get the first result:

using System;
using System.Collections.Generic;
using System.Linq;
   using Newtonsoft.Json.Linq;

// …

static void Main(string[] args)
{
  var obj = JObject.Parse(json);

  var titles = obj.SelectTokens("$.store.book[*].title");

  Console.WriteLine(titles.First());
} 

How it works…

The SelectTokens method of JObject takes a JSONPath expression...