首页 > 解决方案 > 从 youtube api 调用中恢复 json 数据

问题描述

我执行了代码以从订阅者那里检索信息,一切都很好,但问题是我无法获取 json 格式的信息

<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for youtube.subscriptions.list
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/guides/code_samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("AIzxxxxxxxxxxx");
    return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.youtube.subscriptions.list({
      "part": [
        "snippet,contentDetails"
      ],
      "forChannelId": "UCASxxxxxxxxxxxx",
      "mine": true
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
                
                
                ?????????????

              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "5000000020-au42cxxxxxxxxxxxx.apps.googleusercontent.com"});
  });
</script>

我查看了控制台,发现信息是在响应中检索到的,但不是 json 格式

在此处输入图像描述

标签: javascriptphpapiyoutube

解决方案


获得 API 的响应后,您需要检查其内容并获取所需的值。

例子:

.then(function(response) {
    // This is the response of the API.
    console.log(response);

    // Once you got the response, view its content.
    // For example, if you want get the "results" value 
    // of the "response", use: 
    console.log(response.results);
  },
  function(err) {
    console.error("Execute error", err);
  });

推荐阅读