Parsing JSON in Controller w/ HTTParty

gbdev picture gbdev · Aug 19, 2013 · Viewed 25.5k times · Source

In my controller I have the following code...

response = HTTParty.get('https://graph.facebook.com/zuck')
logger.debug(response.body.id)

I am getting a NoMethodError / undefined method `id'

If I do...

logger.debug(response.body)

It outputs as it should...

{"id":"4","name":"Mark Zuckerberg","first_name":"Mark","last_name":"Zuckerberg","link":"http:\/\/www.facebook.com\/zuck","username":"zuck","gender":"male","locale":"en_US"}

One would think it's response.body.id, but obviously that's not working. Thanks in advance!

Answer

Niall Paterson picture Niall Paterson · Aug 19, 2013

Try this:

body = JSON.parse(response.body)
id = body["id"]

For this kind of thing, I'd recommend either a) using Koala or b) create a class using httparty. You can then set format: json to auto parse the returned json. See here and here