简体   繁体   English

API中的JSON格式错误

[英]Malformed JSON from API

I'm currently using an API and getting the following results for my GET request: 我目前正在使用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"}]

I want to be able to get each title & post, but my basic knowledge of JSON would tell me that I need to declare each part of the array, like this: 我希望能够获取每个标题和帖子,但是我对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"}]

Does anyone have any ideas as to how I can iterate through this into HTML? 是否有人对我如何将其迭代到HTML有任何想法?

Thanks. 谢谢。

The first one is an array containing two objects, the second is an array with a named object, containig two child objects. 第一个是包含两个对象的数组,第二个是包含命名对象的数组,包含两个子对象。 Your second example won't work, because you're assigning array elements names (data, post) while arrays are auto-indexed with integers. 您的第二个示例将不起作用,因为您正在分配数组元素名称(数据,后),而数组是使用整数自动索引的。 The syntax is simply invalid. 语法完全无效。

Using the result you get from the API, you first need to convert it into an object. 使用从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"}]');

After this, you can simply iterate over the array: 之后,您可以简单地遍历数组:

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

The above will output 以上将输出

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

Here is a working jsfiddle of the solution at http://jsfiddle.net/4WxFk/3/ 这是该解决方案的有效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