Search code examples
json.netjsonpath

JSON.net : get path of a JToken when nodes have dot?


There's a property Path on JToken. But it escapes the name of object with "[' ']" if the object name contains a "."

  • XPATH : dir/nested_dir/file.txt
  • JSON: dir.nested_dir.['file.txt']

Is there some other property that will return the path as an array of string ?


Solution

  • There is not a built-in property that does this, but you can make an extension method that does what you want easily enough:

    public static class JsonExtensions
    {
        public static string[] PathAsArray (this JToken token)
        {
            return token.AncestorsAndSelf()
                        .OfType<JProperty>()
                        .Select(p => p.Name)
                        .Reverse()
                        .ToArray();
        }
    }
    

    Then use it like this:

    var pathArray = token.PathAsArray();
    Console.WriteLine(string.Join("/", pathArray));
    

    Fiddle: https://dotnetfiddle.net/GOdo7t

    Note: the above extension method ignores any JArrays that might be in the path. You will need to make adjustments to the code if you need to handle arrays.