繁体   English   中英

API中的JSON格式错误

[英]Malformed JSON from API

我目前正在使用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有任何想法?

谢谢。

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

使用从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

这是该解决方案的有效jsfiddle,位于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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM