Samir Shah Samir Shah - 3 years ago 191
CoffeeScript Question

HUBOT Coffescript - JSON obejct

Wondering if anyone can help me with this - pretty much novice in scripting and not sure if I'm doing it right. I need to get an object from this JSON string and it keeps giving me "undefined" error.

Here's the JSON:

{ data:
[ { type: 'gif',
id: 'Cmr1OMJ2FN0B2',
slug: 'hello-Cmr1OMJ2FN0B2',
url: '',
bitly_gif_url: '',
bitly_url: '',
embed_url: '',
username: '',
source: '',
rating: 'g',
content_url: '',
source_tld: '',
source_post_url: '',
is_indexable: 0,
import_datetime: '2016-09-05 13:48:36',
trending_datetime: '2017-09-19 14:26:18',
images: [Object],
title: 'bom dia hello GIF' } ],
pagination: { total_count: 2516, count: 1, offset: 0 },
{ status: 200,
msg: 'OK',
response_id: '5a28576867382f644dc7d33b' } }

And here's my HUBOT script:

robot.hear /^(no)$|^.*(\sno\s).*$/i, (res) ->
api_url = ''
path = '/v1/gifs/search'
url = "#{api_url}#{path}"
q: "nono+penguin"
rating: 'g'
limit: 1
fmt: 'json'
.header('api_key', giphyAuthToken)
.header('Content-Type', 'application/json')
.get() (err, res, body) ->
# error checking code here
if err
console.log err
data = JSON.parse(body)
console.log data #this prints above data
console.log " giphy response"
console.log data.images.original.url #This is giving error that original is undefined

Wondering how can I access this "images" object from Giphy's response.


Answer Source

The data field in your object is an Array so you need to put the index in order to access the content, i.e.

data = JSON.parse(body)
console.log data[0].images
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download