0

I have JSON string like below :

{
    "ConfigurationJsonResult":
    [
        2246,
        2247,
        2248,
        2249,
        2250,
        2251,
        2252,
        2253,
        2254,
        2255
    ]
}

My problem is i want to get 1st value i.e 2246 using xPath.

I have tried using /ConfigurationJsonResult[1] but it gives me [2246,2247.....2255], i just want 2246. How to achieve it.

5
  • Is it possible to navigate a JSON String with XPath?? Commented Dec 5, 2013 at 6:26
  • yes , read here goessner.net/articles/JsonPath Commented Dec 5, 2013 at 6:27
  • 2
    It is called JSONPath according to the link and it is not XPath Commented Dec 5, 2013 at 6:29
  • but you can read json values using XPath..... Commented Dec 5, 2013 at 6:31
  • 3
    @Popeye the link you have posted describes a library to parse json data using jsonpath which is analogous to xpath but not xpath itself. With standard js functions you cannot do it. However you can translate a xpath to jsonpath and do it using simple function. Commented Dec 5, 2013 at 6:38

1 Answer 1

1

You can write a mapping function to convert xpath to jsonpath and use converted string to access the data.

function xpathToJsonPath(xpath) {
   var jsonPath = xpath.replace("//","..");
   //Simillarly other mappings
   return jsonPath;
}

var data = jsonPath(object, xpathToJsonPath("$..author"));

Mappings are given the link you have shared - http://goessner.net/articles/JsonPath/

You can do plenty of improvements on this like extending this as a function to prototype etc.

Sign up to request clarification or add additional context in comments.

1 Comment

In some regards such a translation is actually a nice idea. It's also possible to take a json file, json.reads() it and then print it as xml to use libxml2 support. For the given usecase it's too much of an overhead though, imho.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.