Walker Walker - 27 days ago 7
JSON Question

rails - call json api and parse one value in response

I'm calling a json api and retrieving this as the result every single time:

{
"@endDate": "2016-11-05",
"@metric": "Sessions",
"@startDate": "2016-11-05",
"@generatedDate": "11\/5\/16 6:14 PM",
"@version": "1.0",
"day": {
"@date": "2016-11-05",
"@value": "8174"
}
}


I want to get the number 8174 in a variable in rails, how do I do this?

Answer

Assign your json response to result variable

result = { "@endDate": "2016-11-05", "@metric": "Sessions", "@startDate": "2016-11-05", "@generatedDate": "11\/5\/16 6:14 PM", "@version": "1.0", "day": { "@date": "2016-11-05", "@value": "8174" } }

Parse it

hash_result = JSON.parse(result.to_josn)

After parsing hash_result is now a hash.

get_number = hash_result['day']['@value']

Comments