【问题标题】:Unable to get a specific value on a JSON object无法获取 JSON 对象的特定值
【发布时间】:2015-02-11 03:16:39
【问题描述】:

我正在使用 Facebook Javascript SDK 获取收件箱消息,到目前为止,我能够获取它们并将其转换为 JSON 对象

function getMsgs() { FB.api( "/me/inbox", function (response) { if (response && !response.error) { var result = JSON.stringify(response); document.getElementById("msgs").innerHTML="<pre>"+result+"</pre>"; } } ); } 我最终得到的是这样的:

{ "data":[ { "id":"15986833470221166", "to":{ "data":[ { "id":"7888047207869023", "name":"My Name" }, { "id":"101530783476778608", "name":"Friend Name" } ] }, "updated_time":"2015-02-08T03:09:02+0000", "unread":5, "unseen":0, "comments":{ "data":[ { "id":"159268645347021166_1421118060", "from":{ "id":"7888047207869023", "name":"My Name" }, "message":"blah blah blah", "created_time":"2015-01-13T03:01:00+0000" }, { "id":"159268645347021166_1421118060", "from":{ "id":"7888047207869023", "name":"My Name" }, "message":"blah blah blah", "created_time":"2015-01-13T03:01:16+0000" }, { "id":"159268645347021166_1421118060", "from":{ "id":"101530783476778608", "name":"Friend Name" }, "message":"blah blah blah", "created_time":"2015-01-13T03:01:23+0000" }, { "id":"159268645347021166_1421118060", "from":{ "id":"101530783476778608", "name":"Friend Name" }, "message":"blah blah blah", "created_time":"2015-01-13T03:01:30+0000" }, { "id":"159268645347021166_1421118060", "from":{ "id":"101530783476778608", "name":"Friend Name" }, "message":"blah blah blah", "created_time":"2015-02-08T03:09:02+0000" } ], "paging":{ "previous":"https://graph.facebook.com/v2.2/15986453474543021166/comments?access_token=TOKEN&limit=25&since=1423364314942&__paging_token=TOKEN&__previous=1", "next":"https://graph.facebook.com/v2.2/15986453474543021166/comments?access_token=TOKEN&limit=25&until=142111148324060&__paging_token=TOEKN" } } }

我想访问“消息”值。我想创建一个数组来存储这个 JSON 结构中的每个消息值。

【问题讨论】:

  • 您可以在data[0].comments.data上循环播放

标签: javascript json facebook facebook-graph-api facebook-javascript-sdk


【解决方案1】:

如果您只需要获取消息,则可以使用

  if (response && !response.error) {
      var m=null
          , result=JSON.stringify(response)
          , re=/"message":"([^"]+)"/g
          , messages=[];
      while( m=re.exec(result) ) {
          messages.push(m[1]);
      }
      // messages array should now hold all the values by key "message"
      //console.log(messages);
  }

【讨论】:

    【解决方案2】:

    根据您提供的json,您可以执行以下操作:

    // loop through the comments array
    for ( var i = 0 ; i < json.data[0].comments.data.length; i++ )
    {
        var d = json.data[0].comments.data[i];
        // codes here. Message is d.message
    
    }
    

    SAMPLE

    【讨论】:

    • 这是有道理的,您的示例有效,但由于某种原因它不适用于我的代码。也许是因为 JSON 对象比我在这里发布的小 sn-p 大得多。
    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多