This is not valid JSON due to the trailing commas within your hashes. If you fix the commas, minify the JSON to make it easier to work with, and save it as a string, then you can begin to work with it in Ruby:
json = '{"testimonials":[{"office":"Test","authors":"Benjamin"},{"office":"consultant","authors":"Maxime "},{"office":"DAF","authors":"Alexandre"},{"office":"CEO","authors":"Raphaël"},{"office":"Consultant","authors":"Alexis"},{"office":"CEO,","authors":"Sylvain"}]}'
Now parse it into a real Ruby object:
hash = JSON.parse(json)
=> {
"testimonials" => [
[0] {
"office" => "Test",
"authors" => "Benjamin"
},
[1] {
"office" => "consultant",
"authors" => "Maxime "
},
[2] {
"office" => "DAF",
"authors" => "Alexandre"
},
[3] {
"office" => "CEO",
"authors" => "Raphaël"
},
[4] {
"office" => "Consultant",
"authors" => "Alexis"
},
[5] {
"office" => "CEO,",
"authors" => "Sylvain"
}
]
}
This is a hash that has an array of hashes inside it. You should access it using the standard methods for Hash and Array.
Start by getting the value of the only key in the hash, which is an array:
array = hash['testimonials']
=> [
[0] {
"office" => "Test",
"authors" => "Benjamin"
},
[1] {
"office" => "consultant",
"authors" => "Maxime "
},
[2] {
"office" => "DAF",
"authors" => "Alexandre"
},
[3] {
"office" => "CEO",
"authors" => "Raphaël"
},
[4] {
"office" => "Consultant",
"authors" => "Alexis"
},
[5] {
"office" => "CEO,",
"authors" => "Sylvain"
}
]
You indicated you wanted to fetch a value from index 4:
sub_hash = array[4]
=> {
"office" => "Consultant",
"authors" => "Alexis"
}
And that you wanted to return the string Alexis:
string = sub_hash['authors']
=> "Alexis"
Or put it all together in one line:
string = hash['testimonials'][4]['authors']
=> "Alexis"
Or one even shorter line:
JSON.parse(json)['testimonials'][4]['authors']
=> "Alexis"
'Alexis'is the value of some key of some nested hash of some nested array. If so,puts 'Alexis'is all you need. If you don't know if there is such a value do you wish to returntrueorfalse, depending on whether ifh[:testimonials][i][:authors] == 'Alexis'"for somei, implying you are aware of the structure of the hash?...trueorfalseyou wish to returng ={ "office": "Consultant", "authors": "Alexis", so that, for example, you could computeg[:office] #=> "Consultant", that corresponds with:authorshaving a value"Alexis". This is an example of trying to state a question unambiguously in terms of an example. Please edit to clarify.