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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With