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?

Christophe Geers
  • 8,564
  • 3
  • 37
  • 53
Niels Bosma
  • 11,758
  • 29
  • 89
  • 148
  • 4
    Might I suggest Json.NET as an alternative JSON parser (http://james.newtonking.com/pages/json-net.aspx) – Christophe Geers Sep 24 '11 at 08:06
  • Does it have a feature similar to JsonPath? – Niels Bosma Sep 24 '11 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: http://stackoverflow.com/questions/1698175/what-is-the-json-net-equivilant-of-xmls-xpath-selectnodes-selectsinglenode – Christophe Geers Sep 24 '11 at 13:52
  • Well... it wasn't I need JsonPath for it's filter functionality. – Niels Bosma Sep 29 '11 at 05:45
  • Might I suggest Manatee.Json as an alternative JSON Parser (https://bitbucket.org/gregsdennis/manatee.json). I'm currently working on native JsonPath, and its implementation is significantly easier to use than Json.Net and JsonPath.Net. It should be ready for release in a week or two. – gregsdennis Aug 26 '14 at 20:05
  • 1
    Just as a followup, Manatee.Json's implementation of JsonPath is now available on Nuget. – gregsdennis Apr 14 '15 at 02:53
  • 1
    For further readers - Json.NET fully supports JsonPath via SelectToken http://james.newtonking.com/archive/2014/02/01/json-net-6-0-release-1-%E2%80%93-jsonpath-and-f-support – DrAlligieri Aug 20 '15 at 10:17
  • If I could add, JsonCons.JsonPath is now available on Nuget, and supports querying JsonDocument/JsonElement instances. Lots of code examples at https://github.com/danielaparker/JsonCons.Net/blob/main/examples/JsonPath.Examples/JsonPathExamples.cs. – Daniel Aug 10 '21 at 19:03

4 Answers4

27

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:

Rick Sladkey
  • 33,988
  • 6
  • 71
  • 95
  • 3
    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"); – L.B Sep 30 '11 at 13:20
  • 1
    This answer answers the question. There are of course many other approaches depending on the problem being solved. – Rick Sladkey Sep 30 '11 at 16:30
  • Thanks! Exactly what I needed. Json.Net's SelectToken don't have the functionality I need. – Niels Bosma Oct 01 '11 at 06:37
  • A beautifully crafted answer, thank you! Exactly what I was looking for too. – Jeremy Bull Nov 18 '12 at 04:15
  • 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 http://stackoverflow.com/questions/16566359/jsonpathscriptevaluator-implementation-for-jsonpath-in-c-sharp-for-handling-ex – Ravi Gupta May 15 '13 at 13:32
  • This is an awesome answer but none of the filters work. `$..book[?(@.price<10)]` – Donny V. May 28 '13 at 21:10
  • Did anyone else following this answer create a working implementation of JsonPathScriptEvaluator to make the filters work? I'm about to take a stab at it and I'd appreciate any advice. – firechant Aug 21 '13 at 15:24
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();
Led Tapgar
  • 41
  • 5
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);
}
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
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");
AnthonyVO
  • 3,821
  • 1
  • 36
  • 41