Ошибка чтения ответа JSON Google Script API Twitter

Я использую twitter API для получения данных в Google Script. Я использую библиотеку Twitterlib (https://github.com/airhadoken/twitter-lib ) для авторизации, и эта часть работает хорошо. Однако ответ, который я получаю от твиттера, json, когда я его разбираю - он продолжает давать мне [Object] [Object] - переменную данных в коде. Что я делаю неправильно?

function getHTI() {
  
  var twitterKeys= {                                                                        //Twitter Authentication Tokens to pass through props
    TWITTER_CONSUMER_KEY: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    TWITTER_CONSUMER_SECRET: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    TWITTER_ACCESS_TOKEN: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    TWITTER_ACCESS_SECRET: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"    
  }

  var props = PropertiesService.getScriptProperties();

  props.setProperties(twitterKeys);
  
  var params = new Array(0);
 
  var service = new Twitter.OAuth(props);                                                   //Twitter Service Header for Authorization

  if (!service.hasAccess() ) {                                                              //Determining if there is access

    console.log("Authentication Failed");
  } else {
    console.log("Authentication Successful");                                               //Log: if Authentication is Successful
    }
  
///////////////////////////////////////////////////////////////////////////////////////////////////////
//         Getting Data 
//////////////////////////////////////////////////////////////////////////////////////////////////////
  var dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Carib');
  var look = 'https://api.twitter.com/1.1/search/tweets.json?q=ka%20from%3AMsppOfficiel&result_type=recent&count=1&tweet_mode=extended';  //Query text
        
  var response = service.fetch(look);                                                       //Actual Twitter Query
  var data = JSON.parse(response.getContentText());                                         //Parsing Response as JSON
  Logger.log("JSON unparsed data is "+ response);
  Logger.log("JSON parsed data is "+ data);
}

Ответ, который я получаю

JSON unparsed data is 
{"statuses":[{"created_at":"Wed Jul 08 05:35:22 +0000 2020","id":1280737220123484160,"id_str":"1280737220123484160","full_text":"#COVID19 \n#MSPPHaiti\n#UCRP \n\n61 nouvo ka konfime ak 4 moun anplis mouri anba COVID-19 nan dat 6 jiy\u00e8 2020 an nan peyi Dayiti. \nSa ki bay yon total 6,432 ka konfime, 117 moun mouri ak 2,080 moun trete https:\/\/t.co\/uOWb5HNsFD","truncated":false,"display_text_range":[0,199],"entities":{"hashtags":[{"text":"COVID19","indices":[0,8]},{"text":"MSPPHaiti","indices":[10,20]},{"text":"UCRP","indices":[21,26]}],"symbols":[],"user_mentions":[],"urls":[],"media":[{"id":1280737107787595779,"id_str":"1280737107787595779","indices":[200,223],"media_url":"http:\/\/pbs.twimg.com\/media\/EcYXnShXQAM73Pq.jpg","media_url_https":"https:\/\/pbs.twimg.com\/media\/EcYXnShXQAM73Pq.jpg","url":"https:\/\/t.co\/uOWb5HNsFD","display_url":"pic.twitter.com\/uOWb5HNsFD","expanded_url":"https:\/\/twitter.com\/MsppOfficiel\/status\/1280737220123484160\/photo\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":1200,"h":857,"resize":"fit"},"small":{"w":680,"h":486,"resize":"fit"},"large":{"w":2048,"h":1463,"resize":"fit"}}}]},"extended_entities":{"media":[{"id":1280737107787595779,"id_str":"1280737107787595779","indices":[200,223],"media_url":"http:\/\/pbs.twimg.com\/media\/EcYXnShXQAM73Pq.jpg","media_url_https":"https:\/\/pbs.twimg.com\/media\/EcYXnShXQAM73Pq.jpg","url":"https:\/\/t.co\/uOWb5HNsFD","display_url":"pic.twitter.com\/uOWb5HNsFD","expanded_url":"https:\/\/twitter.com\/MsppOfficiel\/status\/1280737220123484160\/photo\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":1200,"h":857,"resize":"fit"},"small":{"w":680,"h":486,"resize":"fit"},"large":{"w":2048,"h":1463,"resize":"fit"}}}]},"metadata":{"iso_language_code":"ht","result_type":"recent"},"source":"\u003ca href=\"https:\/\/mobile.twitter.com\" rel=\"nofollow\"\u003eTwitter Web App\u003c\/a\u003e","in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":996837919334813696,"id_str":"996837919334813696","name":"MINIST\u00c8RE DE LA SANT\u00c9 PUBLIQUE ET DE LA POPULATION","screen_name":"MsppOfficiel","location":"Haiti","description":"Compte Twitter officiel du Minist\u00e8re de la Sant\u00e9 Publique et de la Population (MSPP) \nKont Twit\u00e8 ofisy\u00e8l Minist\u00e8 Sante Piblik ak Popilasyon (MSPP)","url":"https:\/\/t.co\/YqrCoO9WxE","entities":{"url":{"urls":[{"url":"https:\/\/t.co\/YqrCoO9WxE","expanded_url":"http:\/\/mspp.gouv.ht","display_url":"mspp.gouv.ht","indices":[0,23]}]},"description":{"urls":[]}},"protected":false,"followers_count":26325,"friends_count":420,"listed_count":26,"created_at":"Wed May 16 19:40:55 +0000 2018","favourites_count":158,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":543,"lang":null,"contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"000000","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/996840392892002304\/1gY6JC-8_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/996840392892002304\/1gY6JC-8_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/996837919334813696\/1529003460","profile_link_color":"7FDBB6","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"has_extended_profile":false,"default_profile":false,"default_profile_image":false,"following":false,"follow_request_sent":false,"notifications":false,"translator_type":"none"},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":7,"favorite_count":2,"favorited":false,"retweeted":false,"possibly_sensitive":false,"lang":"ht"}],"search_metadata":{"completed_in":0.021,"max_id":1280737220123484160,"max_id_str":"1280737220123484160","next_results":"?max_id=1280737220123484159&q=ka%20from%3AMsppOfficiel&count=1&include_entities=1&result_type=recent","query":"ka+from%3AMsppOfficiel","refresh_url":"?since_id=1280737220123484160&q=ka%20from%3AMsppOfficiel&result_type=recent&include_entities=1","count":1,"since_id":0,"since_id_str":"0"}}
JSON parsed data is [object Object]



person Prabhjot    schedule 04.07.2020    source источник
comment
Можете ли вы предоставить общий доступ к response очищенному объекту?   -  person Jeff Rush    schedule 06.07.2020
comment
@ jeff-rush Я добавил ответ к вопросу, как вы просили.   -  person Prabhjot    schedule 08.07.2020
comment
Хорошо, но вы можете работать с response напрямую, например, если вы хотите получить full_text, просто используйте response.statuses[0].full_text, и вы получите # COVID19 #MSPPHaiti #UCRP 61 и т. Д. И т. Д.. Разве не то, что вы хотели?   -  person Jeff Rush    schedule 09.07.2020
comment
Я попытался сделать то, что вы предложили @JeffRush, используя этот код: Logger.log("Getting data by keys is "+ response.statuses[0].full_text);, и получил этот ответ [20-07-10 18:08:30:863 EDT] TypeError: Cannot read property '0' of undefined at getHTI(Twitter:38:59)' . Я думаю, это потому, что ответ var не анализируется?   -  person Prabhjot    schedule 11.07.2020


Ответы (1)


Если ответ API представляет собой JSON, подобный предоставленному, вы не делаете ничего плохого, анализируя его. Если это ваш очищенный JSON:

{
  "statuses":[
    {
      "created_at":"Wed Jul 08 05:35:22 +0000 2020",
      "id":1280737220123484160,
      "id_str":"1280737220123484160",
      "full_text":"#COVID19 \n#MSPPHaiti\n#UCRP \n\n61 nouvo ka konfime ak 4 moun anplis mouri anba COVID-19 nan dat 6 jiy\u00e8 2020 an nan peyi Dayiti. \nSa ki bay yon total 6,432 ka konfime, 117 moun mouri ak 2,080 moun trete https:\/\/t.co\/uOWb5HNsFD",
      "truncated":false,
      "display_text_range":[
        0,
        199
      ],
      "entities":{
        "hashtags":[
          {
            "text":"COVID19",
            "indices":[
              0,
              8
            ]
          },
          {
            "text":"MSPPHaiti",
            "indices":[
              10,
              20
            ]
          },
          {
            "text":"UCRP",
            "indices":[
              21,
              26
            ]
          }
        ],
        "symbols":[

        ],
        "user_mentions":[

        ],
        "urls":[

        ],
        "media":[
          {
            "id":1280737107787595779,
            "id_str":"1280737107787595779",
            "indices":[
              200,
              223
            ],
            "media_url":"http:\/\/pbs.twimg.com\/media\/EcYXnShXQAM73Pq.jpg",
            "media_url_https":"https:\/\/pbs.twimg.com\/media\/EcYXnShXQAM73Pq.jpg",
            "url":"https:\/\/t.co\/uOWb5HNsFD",
            "display_url":"pic.twitter.com\/uOWb5HNsFD",
            "expanded_url":"https:\/\/twitter.com\/MsppOfficiel\/status\/1280737220123484160\/photo\/1",
            "type":"photo",
            "sizes":{
              "thumb":{
                "w":150,
                "h":150,
                "resize":"crop"
              },
              "medium":{
                "w":1200,
                "h":857,
                "resize":"fit"
              },
              "small":{
                "w":680,
                "h":486,
                "resize":"fit"
              },
              "large":{
                "w":2048,
                "h":1463,
                "resize":"fit"
              }
            }
          }
        ]
      },
      "extended_entities":{
        "media":[
          {
            "id":1280737107787595779,
            "id_str":"1280737107787595779",
            "indices":[
              200,
              223
            ],
            "media_url":"http:\/\/pbs.twimg.com\/media\/EcYXnShXQAM73Pq.jpg",
            "media_url_https":"https:\/\/pbs.twimg.com\/media\/EcYXnShXQAM73Pq.jpg",
            "url":"https:\/\/t.co\/uOWb5HNsFD",
            "display_url":"pic.twitter.com\/uOWb5HNsFD",
            "expanded_url":"https:\/\/twitter.com\/MsppOfficiel\/status\/1280737220123484160\/photo\/1",
            "type":"photo",
            "sizes":{
              "thumb":{
                "w":150,
                "h":150,
                "resize":"crop"
              },
              "medium":{
                "w":1200,
                "h":857,
                "resize":"fit"
              },
              "small":{
                "w":680,
                "h":486,
                "resize":"fit"
              },
              "large":{
                "w":2048,
                "h":1463,
                "resize":"fit"
              }
            }
          }
        ]
      },
      "metadata":{
        "iso_language_code":"ht",
        "result_type":"recent"
      },
      "source":"\u003ca href=\"https:\/\/mobile.twitter.com\" rel=\"nofollow\"\u003eTwitter Web App\u003c\/a\u003e",
      "in_reply_to_status_id":null,
      "in_reply_to_status_id_str":null,
      "in_reply_to_user_id":null,
      "in_reply_to_user_id_str":null,
      "in_reply_to_screen_name":null,
      "user":{
        "id":996837919334813696,
        "id_str":"996837919334813696",
        "name":"MINIST\u00c8RE DE LA SANT\u00c9 PUBLIQUE ET DE LA POPULATION",
        "screen_name":"MsppOfficiel",
        "location":"Haiti",
        "description":"Compte Twitter officiel du Minist\u00e8re de la Sant\u00e9 Publique et de la Population (MSPP) \nKont Twit\u00e8 ofisy\u00e8l Minist\u00e8 Sante Piblik ak Popilasyon (MSPP)",
        "url":"https:\/\/t.co\/YqrCoO9WxE",
        "entities":{
          "url":{
            "urls":[
              {
                "url":"https:\/\/t.co\/YqrCoO9WxE",
                "expanded_url":"http:\/\/mspp.gouv.ht",
                "display_url":"mspp.gouv.ht",
                "indices":[
                  0,
                  23
                ]
              }
            ]
          },
          "description":{
            "urls":[

            ]
          }
        },
        "protected":false,
        "followers_count":26325,
        "friends_count":420,
        "listed_count":26,
        "created_at":"Wed May 16 19:40:55 +0000 2018",
        "favourites_count":158,
        "utc_offset":null,
        "time_zone":null,
        "geo_enabled":false,
        "verified":false,
        "statuses_count":543,
        "lang":null,
        "contributors_enabled":false,
        "is_translator":false,
        "is_translation_enabled":false,
        "profile_background_color":"000000",
        "profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png",
        "profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png",
        "profile_background_tile":false,
        "profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/996840392892002304\/1gY6JC-8_normal.jpg",
        "profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/996840392892002304\/1gY6JC-8_normal.jpg",
        "profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/996837919334813696\/1529003460",
        "profile_link_color":"7FDBB6",
        "profile_sidebar_border_color":"000000",
        "profile_sidebar_fill_color":"000000",
        "profile_text_color":"000000",
        "profile_use_background_image":false,
        "has_extended_profile":false,
        "default_profile":false,
        "default_profile_image":false,
        "following":false,
        "follow_request_sent":false,
        "notifications":false,
        "translator_type":"none"
      },
      "geo":null,
      "coordinates":null,
      "place":null,
      "contributors":null,
      "is_quote_status":false,
      "retweet_count":7,
      "favorite_count":2,
      "favorited":false,
      "retweeted":false,
      "possibly_sensitive":false,
      "lang":"ht"
    }
  ],
  "search_metadata":{
    "completed_in":0.021,
    "max_id":1280737220123484160,
    "max_id_str":"1280737220123484160",
    "next_results":"?max_id=1280737220123484159&q=ka%20from%3AMsppOfficiel&count=1&include_entities=1&result_type=recent",
    "query":"ka+from%3AMsppOfficiel",
    "refresh_url":"?since_id=1280737220123484160&q=ka%20from%3AMsppOfficiel&result_type=recent&include_entities=1",
    "count":1,
    "since_id":0,
    "since_id_str":"0"
  }
}

Вы можете создать на его основе документ, используя _ 2_. Вы можете взаимодействовать с ним, используя Document.getDescendants() как один вариант.

person Jacques-Guzel Heron    schedule 14.07.2020