Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 491
CodeGuru Avatar asked Aug 04 '26 15:08

CodeGuru


1 Answers

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
like image 98
Michael Kruglos Avatar answered Aug 06 '26 06:08

Michael Kruglos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!