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!
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With