Walker
Walker

Reputation: 1147

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?

Upvotes: 1

Views: 258

Answers (1)

Junan Chakma
Junan Chakma

Reputation: 651

Assign your json response to response variable

response = { "@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

parsed_response = JSON.parse(response.to_josn)

After parsing parsed_response is now a hash. So you can access the number from parsed_response hash

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

Upvotes: 1

Related Questions