来自API的格式错误的JSON

时间:2014-03-12 05:03:21

标签: javascript json httprequest

我目前正在使用API​​,并为我的GET请求获得以下结果:

[{"id" : 123456, "title" : "hello world", "post" : "this is the actually text of the    blog"}, {"id" : 123457, "title" : "hello world 2", "post" : "this is the second blog post"}]

我希望能够得到每个冠军和发布,但我对JSON的基本知识会告诉我,我需要声明数组的每个部分,如下所示:

["data" : {"id" : 123456, "title" : "hello world", "post" : "this is the actually text of the    blog"}, "data" : {"id" : 123457, "title" : "hello world 2", "post" : "this is the second blog post"}]

有没有人对如何将其迭代到HTML中有任何想法?

感谢。

2 个答案:

答案 0 :(得分:0)

第一个是包含两个对象的数组,第二个是带有命名对象的数组,包含两个子对象。您的第二个示例将不起作用,因为您正在分配数组元素名称(data,post),而数组是使用整数自动索引的。语法无效。

使用从API获得的结果,首先需要将其转换为对象。

resultObject = JSON.parse('[{"id" : 123456, "title" : "hello world", "post" : "this is the actually text of the    blog"}, {"id" : 123457, "title" : "hello world 2", "post" : "this is the second blog post"}]');

在此之后,您可以简单地遍历数组:

resultObject.forEach(function(e) {
    console.log(e.title + ": " + e.post);
});

以上将输出

hello world: this is the actually text of the    blog
hello world 2: this is the second blog post

答案 1 :(得分:0)

以下是http://jsfiddle.net/4WxFk/3/

解决方案的工作方式
        <div id="response"></div>
<script>
        var res= '[{"id" : "123456", "title" : "hello world", "post" : "this is the actually text of the blog"}, {"id" : "123457", "title" : "hello world 2", "post" : "this is the second blog post"}]'

        var pres = JSON.parse(res)
        $.each(pres, function(){
            console.log(this)
        $("#response").append(this.id + ","+ this.title + "," + this.post)
        })
</script>