Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Look Up any node in Json.NET

I am using NewtonSoft Json.NET library for parsing JSON files in a .NET app. What I need to do is to pass the name of a node, and get the node if it exists, regardless of their level which is unknown beforehand.

For instance in a file:

string json = @"{
  ""Name"": ""Apple"",
  ""Expiry"": new Date(1230422400000),
  ""Price"": 3.99,
  ""ATest"": {
    ""MyTest"":
    [
       ""blah"",
       ""blah""
    ]
  }
}";

Is there a way to just use the value "MyTest" to fetch that node without having to know the parent's name like jObject["ATest"]["MyTest"][0]?

like image 605
Alex Avatar asked Oct 23 '12 14:10

Alex


2 Answers

AFAIK there's no XPath-like query syntax for JToken / JObject, but you can make one fairly easily - see code below.

public static class StackOverflow_13033174
{
    public static void Test()
    {
        string json = @"{ 
                          ""Name"": ""Apple"", 
                          ""Expiry"": new Date(1230422400000), 
                          ""Price"": 3.99, 
                          ""ATest"": { 
                            ""MyTest"": 
                            [ 
                               ""blah"", 
                               ""blah"" 
                            ] 
                          } 
                        }";

        JObject jo = JObject.Parse(json);
        JToken myTest = jo.Descendants()
            .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "MyTest")
            .Select(p => ((JProperty)p).Value)
            .FirstOrDefault();
        Console.WriteLine(myTest);
    }
}
like image 91
carlosfigueira Avatar answered Oct 23 '22 18:10

carlosfigueira


Here is another approach using JSONPath:

See: https://dotnetfiddle.net/EIKjnH

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

                
public static class StackOverflow_13033174
{
    public static void Main()
    {
    string json = @"{ 
                      ""Name"": ""Apple"", 
                      ""Expiry"": new Date(1230422400000), 
                      ""Price"": 3.99, 
                      ""ATest"": { 
                        ""MyTest"": 
                        [ 
                           ""blah"", 
                           ""blah"" 
                        ] 
                      } 
                    }";

    JObject jo = JObject.Parse(json);
    
    JToken myTest = jo.SelectToken("*.MyTest");
    Console.WriteLine(myTest);
    }
}
like image 5
jm. Avatar answered Oct 23 '22 16:10

jm.