Sunday 5 June 2016

Searching JSON objects

With the increased usage of JSON format to describe data for various purpose (storage like Azure Document DB, Mongo DB, Raven DB etc., exchange of data over the wire like WebApi responses), you would inevitably run into scenarios where you need to perform actions like search data, aggregate data etc., that you have been performing on other data formats like XML.

JSON.NET gives you a great library to perform a subset of such operations e.g. searching your JSON object.

Here is an example:

var objString = @"{
                ""id"":""testId"",
                ""data"":[
                    {
                        ""name"":""item1""
                    },
                    {
                        ""name"":""item2""
                    },
                ],
                ""data1"":{
                    ""id"": ""data1"",
                    ""value"":{
                        ""child"": ""data1child"",
                        ""name"":""data1child""
                    }
                }
            }";

            Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.Parse(objString);
            foreach (Newtonsoft.Json.Linq.JToken token in jobject.SelectTokens("$..name"))
            {
                Console.WriteLine(token);
            }


The result would be:

item1
item2
data1child


Let's check out its performance over a large object. I added below lines to the above code.

var itemString = @"{
                        ""name"":""item{0}""
                    }";
            for(int i = 0; i < 10000; i++)
            {
                jobject["data" + i.ToString()] = Newtonsoft.Json.Linq.JObject.Parse(itemString.Replace("{0}", i.ToString()));
            }

            Stopwatch sw = new Stopwatch();
            sw.Start();
            var searchResults = jobject.SelectTokens("$..name");
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);


The result is less than 1 millisecond. Not bad!!

No comments:

Post a Comment