20

I'm trying to use JsonPath for .NET (http://code.google.com/p/jsonpath/downloads/list) and I'm having trouble finding an example of how to parse a Json string and a JsonPath string and get a result.

Has anyone used this?

8
  • 4
    Might I suggest Json.NET as an alternative JSON parser (james.newtonking.com/pages/json-net.aspx) Commented Sep 24, 2011 at 8:06
  • Does it have a feature similar to JsonPath? Commented Sep 24, 2011 at 13:44
  • 3
    Something similar to XPath? It does. Check out the SelectToken functionality of JSON.NET. You can use a string expression to get JSON. For example: stackoverflow.com/questions/1698175/… Commented Sep 24, 2011 at 13:52
  • 1
    Just as a followup, Manatee.Json's implementation of JsonPath is now available on Nuget. Commented Apr 14, 2015 at 2:53
  • 1
    For further readers - Json.NET fully supports JsonPath via SelectToken james.newtonking.com/archive/2014/02/01/… Commented Aug 20, 2015 at 10:17

4 Answers 4

27
+100

The problem you are experiencing is that the C# version of JsonPath does not include a Json parser so you have to use it with another Json framework that handles serialization and deserialization.

The way JsonPath works is to use an interface called IJsonPathValueSystem to traverse parsed Json objects. JsonPath comes with a built-in BasicValueSystem that uses the IDictionary interface to represent Json objects and the IList interface to represent Json arrays.

You can create your own BasicValueSystem-compatible Json objects by constructing them using C# collection initializers but this is not of much use when your Json is coming in in the form of strings from a remote server, for example.

So if only you could take a Json string and parse it into a nested structure of IDictionary objects, IList arrays, and primitive values, you could then use JsonPath to filter it! As luck would have it, we can use Json.NET which has good serialization and deserialization capabilities to do that part of the job.

Unfortunately, Json.NET does not deserialize Json strings into a format compatible with the BasicValueSystem. So the first task for using JsonPath with Json.NET is to write a JsonNetValueSystem that implements IJsonPathValueSystem and that understands the JObject objects, JArray arrays, and JValue values that JObject.Parse produces.

So download both JsonPath and Json.NET and put them into a C# project. Then add this class to that project:

public sealed class JsonNetValueSystem : IJsonPathValueSystem
{
    public bool HasMember(object value, string member)
    {
        if (value is JObject)
                return (value as JObject).Properties().Any(property => property.Name == member);
        if (value is JArray)
        {
            int index = ParseInt(member, -1);
            return index >= 0 && index < (value as JArray).Count;
        }
        return false;
    }

    public object GetMemberValue(object value, string member)
    {
        if (value is JObject)
        {
            var memberValue = (value as JObject)[member];
            return memberValue;
        }
        if (value is JArray)
        {
            int index = ParseInt(member, -1);
            return (value as JArray)[index];
        }
        return null;
    }

    public IEnumerable GetMembers(object value)
    {
        var jobject = value as JObject;
        return jobject.Properties().Select(property => property.Name);
    }

    public bool IsObject(object value)
    {
        return value is JObject;
    }

    public bool IsArray(object value)
    {
        return value is JArray;
    }

    public bool IsPrimitive(object value)
    {
        if (value == null)
            throw new ArgumentNullException("value");

        return value is JObject || value is JArray ? false : true;
    }

    private int ParseInt(string s, int defaultValue)
    {
        int result;
        return int.TryParse(s, out result) ? result : defaultValue;
    }
}

Now with all three of these pieces we can write a sample JsonPath program:

class Program
{
    static void Main(string[] args)
    {
        var input = @"
              { ""store"": {
                    ""book"": [ 
                      { ""category"": ""reference"",
                            ""author"": ""Nigel Rees"",
                            ""title"": ""Sayings of the Century"",
                            ""price"": 8.95
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""Evelyn Waugh"",
                            ""title"": ""Sword of Honour"",
                            ""price"": 12.99
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""Herman Melville"",
                            ""title"": ""Moby Dick"",
                            ""isbn"": ""0-553-21311-3"",
                            ""price"": 8.99
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""J. R. R. Tolkien"",
                            ""title"": ""The Lord of the Rings"",
                            ""isbn"": ""0-395-19395-8"",
                            ""price"": 22.99
                      }
                    ],
                    ""bicycle"": {
                      ""color"": ""red"",
                      ""price"": 19.95
                    }
              }
            }
        ";
        var json = JObject.Parse(input);
        var context = new JsonPathContext { ValueSystem = new JsonNetValueSystem() };
        var values = context.SelectNodes(json, "$.store.book[*].author").Select(node => node.Value);
        Console.WriteLine(JsonConvert.SerializeObject(values));
        Console.ReadKey();
    }
}

which produces this output:

["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]

This example is based on the Javascript sample at the JsonPath site:

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

7 Comments

Instead of writing a lot of code and using two libraries, wouldn't it be easier to use just Json.Net like this: JObject json = JObject.Parse(@input); var values = json.SelectToken("store.book").Values("author");
This answer answers the question. There are of course many other approaches depending on the problem being solved.
Thanks! Exactly what I needed. Json.Net's SelectToken don't have the functionality I need.
A beautifully crafted answer, thank you! Exactly what I was looking for too.
Hi Rick, I was trying you example with expressions in JsonPath and it seems that in order to support that I have to implement JsonPathScriptEvaluator just like you have implemented IJsonPathValueSystem. Do you have any sample implementation for the same? I have also posted a separate question stackoverflow.com/questions/16566359/…
|
3

using Newtonsoft.Json.Linq yo can use function SelectToken and try out yous JsonPath Check documentation https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

Object jsonObj = JObject.Parse(stringResult);

JToken pathResult = jsonObj.SelectToken("results[0].example");

return pathResult.ToString();

Comments

2

For those that don't like LINQ (.NET 2.0):

namespace JsonPath
{


    public sealed class JsonNetValueSystem : IJsonPathValueSystem
    {


        public bool HasMember(object value, string member)
        {
            if (value is Newtonsoft.Json.Linq.JObject)
            {
                // return (value as JObject).Properties().Any(property => property.Name == member);

                foreach (Newtonsoft.Json.Linq.JProperty property in (value as Newtonsoft.Json.Linq.JObject).Properties())
                {
                    if (property.Name == member)
                        return true;
                }

                return false;
            }

            if (value is Newtonsoft.Json.Linq.JArray)
            {
                int index = ParseInt(member, -1);
                return index >= 0 && index < (value as Newtonsoft.Json.Linq.JArray).Count;
            }
            return false;
        }


        public object GetMemberValue(object value, string member)
        {
            if (value is Newtonsoft.Json.Linq.JObject)
            {
                var memberValue = (value as Newtonsoft.Json.Linq.JObject)[member];
                return memberValue;
            }
            if (value is Newtonsoft.Json.Linq.JArray)
            {
                int index = ParseInt(member, -1);
                return (value as Newtonsoft.Json.Linq.JArray)[index];
            }
            return null;
        }


        public System.Collections.IEnumerable GetMembers(object value)
        {
            System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();

            var jobject = value as Newtonsoft.Json.Linq.JObject;
            /// return jobject.Properties().Select(property => property.Name);

            foreach (Newtonsoft.Json.Linq.JProperty property in jobject.Properties())
            { 
                ls.Add(property.Name);
            }

            return ls;
        }


        public bool IsObject(object value)
        {
            return value is Newtonsoft.Json.Linq.JObject;
        }


        public bool IsArray(object value)
        {
            return value is Newtonsoft.Json.Linq.JArray;
        }


        public bool IsPrimitive(object value)
        {
            if (value == null)
                throw new System.ArgumentNullException("value");

            return value is Newtonsoft.Json.Linq.JObject || value is Newtonsoft.Json.Linq.JArray ? false : true;
        }


        private int ParseInt(string s, int defaultValue)
        {
            int result;
            return int.TryParse(s, out result) ? result : defaultValue;
        }


    }


}

Usage:

object obj = Newtonsoft.Json.JsonConvert.DeserializeObject(input);

JsonPath.JsonPathContext context = new JsonPath.JsonPathContext { ValueSystem = new JsonPath.JsonNetValueSystem() };

foreach (JsonPath.JsonPathNode node in context.SelectNodes(obj, "$.store.book[*].author"))
{
    Console.WriteLine(node.Value);
}

Comments

0

I found that the internal JavaScriptSerializer() can work just fine as long as filtering is not required.

Using the dataset and examples from JsonPath Dataset + Examples

My source for the JsonPath implementation was GitHub

public static string SelectFromJson(string inputJsonData, string inputJsonPath)
{
    // Use the serializer to deserialize the JSON but also to create the snippets
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    serializer.MaxJsonLength = Int32.MaxValue;

    dynamic dynJson = serializer.Deserialize<object>(inputJsonData);

    var jsonPath = new JsonPath.JsonPathContext();
    var jsonResults = jsonPath.Select(dynJson, inputJsonPath);

    var valueList = new List<string>();
    foreach (var node in jsonResults)
    {
        if (node is string)
        {
            valueList.Add(node);
        }
        else
        {
            // If the object is too complex then return a list of JSON snippets
            valueList.Add(serializer.Serialize(node));
        }
    }
    return String.Join("\n", valueList);
}

The function is used as follows.

    var result = SelectFromJson(@"
{ ""store"": {
        ""book"": [ 
            { ""category"": ""fiction"",
                ""author"": ""J. R. R. Tolkien"",
                ""title"": ""The Lord of the Rings"",
                ""isbn"": ""0-395-19395-8"",
                ""price"": 22.99
            }
        ]
    }
}", "$.store.book[*].author");

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.