Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON in Controller w/ HTTParty

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!

like image 387
gbdev Avatar asked Aug 19 '13 18:08

gbdev


People also ask

How do I parse JSON?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What is parsing to JSON?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.

How does JSON parser works?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Does JSON require a parser?

JSON as a string json or profiles. json above, that file actually contains text in the form of a JSON object or array, which happens to look like JavaScript. Just like with text files, if you want to use JSON in your project, you'll need to parse or change it into something your programming language can understand.


1 Answers

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

like image 164
Niall Paterson Avatar answered Oct 22 '22 17:10

Niall Paterson