CodeGuru
CodeGuru

Reputation: 2803

XPath to read array elements from JSON string

I am having JSON output string in the following structure.

{
    "Results": [
        { "Result": 5756 },
        { "Result": 5234 },
        { "Result": 5432 }
    ]
}

From this, I want to access each element (one by one – 5756, 5234, 5432) of “Results” array.

In order to read/extract the element, I am using “XPath”. I have tried many XPaths, however got no luck thus far; following are few of them.

  1. //*[1].Result -- Invalid xPath
  2. //*[1].Result[0] -- Invalid xPath
  3. //*[1]/Result[0] -- NULL
  4. //*[1]/Result -- NULL

And when used //*[1] It gives entire JSON string as following.

[
    { "Result": 5756 },
    { "Result": 5234 },
    { "Result": 5432 }
]

Could you please help me out to resolve the problem I am facing? Or In case, structure of JSON is required to be changed, suggest me new structure along with XPath to access array element, example would be appreciated.

Many thanks in advance.

Upvotes: 3

Views: 10527

Answers (2)

Hakan Bilgin
Hakan Bilgin

Reputation: 1122

@Popeye - I recently released a first version of a JS lib that does exactly what you're looking for; DefiantJS (http://defiantjs.com)

With this lib, you can query any JSON structure with fullscale XPath syntax. You can also use the XPath evaluator to test/verify XPath expressions instantly here:

http://www.defiantjs.com/#xpath_evaluator

As for your example, assuming your result data is as simple as you've examplified, I would suggest a JSON structure like this:

var res = {
    "Results": [
          5756,
          5234,
          5432
    ]
}

And using the XPath evaluator (and see the console on your browser for hints), you can extract the selections you want with this XPath:

var sel = Defiant.search(res, '//Results');
// sel contains the array -> [5276, 5234, 5432]

Upvotes: 2

Michael Kruglos
Michael Kruglos

Reputation: 1286

Here's an example of how you can do it in Ruby, using jsonpath gem (http://rubygems.org/gems/jsonpath):

requre 'json'
require 'jsonpath'

# I initialize the data inline here, but you can read it from file
data = <<-EOS
{
  "Results": [
    { "Result": 5756 },
    { "Result": 5234 },
    { "Result": 5432 }
   ]
}
EOS

json_data = JSON.parse(data)

# First value:
JsonPath.new("$.Results[0].Result").on(json_data) # => 5756

# Second value:
JsonPath.new("$.Results[1].Result").on(json_data) # => 5234

# Third value:
JsonPath.new("$.Results[2].Result").on(json_data) # => 5432

Upvotes: 2

Related Questions