1

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?

1 Answer 1

1

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']

Sign up to request clarification or add additional context in comments.

3 Comments

getting this error ActionView::Template::Error (no implicit conversion of Hash into String): Thank you
By any chance, do you know what would be the best way to call the api? I just realized I worded this questions as if that part was done. Thank you
Edited. I forgot to add to_json. To call an api I usually use rest-client gem and receive the response this way(my answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.