duyn9uyen
duyn9uyen

Reputation: 10311

Get path of JSON value using JSON.NET

I am trying to find a path of a JSON value. Consider the following JSON:

{
    "car": {
        "type": [{
            "sedan": {
                "make": "honda",
                "model": "civics"
            }
        },
        {
            "coupe": {
                "make": "ford",
                "model": "escort"
            }
        }]
    }
}

How can I get the path of the value "honda"? I'm looking to find something like this...

car_type_0_sedan_make_honda

Does JSON.NET support this? I see that there is a JToken.Path property but it is currently not available. http://json.codeplex.com/workitem/24136

Upvotes: 21

Views: 44411

Answers (4)

Axiom255
Axiom255

Reputation: 1397

You could also try the SelectToken method like this:

var j = JObject.Parse(json);
var token = j.SelectToken("car.type[0].sedan.make");
Console.WriteLine(token.Path + " -> " + token.ToString());

Outputs:

car.type[0].sedan.make -> honda

Upvotes: 32

Dennis Rosenbaum
Dennis Rosenbaum

Reputation: 379

There is also a way to retrieve the path just by the value, using linq. You will need Json.NET for this.

JObject jo = JObject.Parse(json);
var token = jo.Descendants()
                    .OfType<JProperty>()
                    .Where(p => p.Value.ToString() == "honda")
                    .First();

        Console.WriteLine(token.Path);

See: https://dotnetfiddle.net/vZ1zLg

Upvotes: 5

Brian Rogers
Brian Rogers

Reputation: 129707

Update to the latest version of Json.NET. The Path property was added to JToken in version 5.0 release 1 (April 7, 2013).

Here is a test program you can use to verify that it works:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""car"": {
                ""type"": [{
                    ""sedan"": {
                        ""make"": ""honda"",
                        ""model"": ""civics""
                    }
                },
                {
                    ""coupe"": {
                        ""make"": ""ford"",
                        ""model"": ""escort""
                    }
                }]
            }
        }";

        JObject obj = JObject.Parse(json);
        JToken token = obj["car"]["type"][0]["sedan"]["make"];
        Console.WriteLine(token.Path + " -> " + token.ToString());
    }
}

Output:

car.type[0].sedan.make -> honda

Upvotes: 20

Sravan
Sravan

Reputation: 1135

you can Convert the Json to dynamic object as below.

JavaScriptSerializer js=new JavaScriptSerializer();
var dataObject=Json.Decode(jsonString);

Then you can reflect over it and find out your string "honda" and construct the path as you like.

Upvotes: -4

Related Questions