2017-12-06 5 views
0

Ich frage mich, ob mir jemand dabei helfen kann - ziemlich Anfänger im Scripting und nicht sicher, ob ich es richtig mache. Ich muss ein Objekt von diesem JSON-String bekommen und es gibt mir immer "undefined" Fehler.HUBOT Coffescript - JSON obejct

Hier ist die JSON:

` 
    { data: 
    [ { type: 'gif', 
     id: 'Cmr1OMJ2FN0B2', 
     slug: 'hello-Cmr1OMJ2FN0B2', 
     url: 'https://giphy.com/gifs/hello-Cmr1OMJ2FN0B2', 
     bitly_gif_url: 'https://gph.is/2bZufS7', 
     bitly_url: 'https://gph.is/2bZufS7', 
     embed_url: 'https://giphy.com/embed/Cmr1OMJ2FN0B2', 
     username: '', 
     source: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo', 
     rating: 'g', 
     content_url: '', 
     source_tld: 'www.fanpop.com', 
     source_post_url: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo', 
     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 }, 
    meta: 
    { status: 200, 
     msg: 'OK', 
     response_id: '5a28576867382f644dc7d33b' } } 
    ` 

Und hier ist mein HUBOT Skript:

` 
    robot.hear /^(no)$|^.*(\sno\s).*$/i, (res) -> 
      api_url = 'https://api.giphy.com' 
      path = '/v1/gifs/search' 
      url = "#{api_url}#{path}" 
      robot.http(url) 
       .query 
        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 
        else 
         data = JSON.parse(body) 
         console.log data #this prints above data 
         console.log "success....got giphy response" 
         console.log data.images.original.url #This is giving error that original is undefined 
         process.exit(1) 
    ` 

fragen sich, wie kann ich diese "Bilder" Objekt zugreifen Giphy Antwort.

Dank

Antwort

1

Das Datenfeld in Ihrem Objekt ist ein Array, so dass Sie den Index in Ordnung zu bringen, um den Inhalt zugreifen zu können, das heißt

data = JSON.parse(body) 
console.log data[0].images 
+0

Dank. Ich kann jetzt zum Array "Bilder" gelangen. Aber "undefined" Fehler, wenn ich versuche, "original.url" Feld zu bekommen. Hier ist der Code: 'data = JSON.parse (Körper) console.log Daten [0] .images [0] .original [0] .url' –

+0

Works jetzt hatte ich einen Tippfehler. Schätze deine Hilfe –