最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Can not parse JSON with JavaScript parser. Square brackets - Stack Overflow

programmeradmin5浏览0评论

I using JavaScript JSON library to parse JSON encoded array, received via POST.

Here is my code:

    var itemsRequest = '[{"id":"142"},{"id":"152"}]';
    var items = JSON.parse(itemsRequest);
    for(var i = 0; i<items.count(); i++)
            {
                var item = items[i];
                alert(item.id);
            }

I am not sure why, but the parser is just not liking that. How can I get it to parse?

I using JavaScript JSON library to parse JSON encoded array, received via POST.

Here is my code:

    var itemsRequest = '[{"id":"142"},{"id":"152"}]';
    var items = JSON.parse(itemsRequest);
    for(var i = 0; i<items.count(); i++)
            {
                var item = items[i];
                alert(item.id);
            }

I am not sure why, but the parser is just not liking that. How can I get it to parse?

Share Improve this question asked Nov 18, 2011 at 0:44 user1052933user1052933 1912 gold badges4 silver badges8 bronze badges 1
  • What does "not liking that" mean? Do you get an error message in the console? What actually happens? What do you get for console.log(items)? – Phrogz Commented Nov 18, 2011 at 0:46
Add a ment  | 

3 Answers 3

Reset to default 4

Try items.length instead of items.count().

An array doesn't have a count method. Use the length property:

for (var i = 0; i < items.length; i++) {

Demo: http://jsfiddle/Guffa/Rt4db/

Below is the very good way to do:

var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = eval(itemsRequest); //Converted to actual JSON data
for (var item in items) {
    alert(items[item]['id']);
}

Hope this is very helpful, thanks

发布评论

评论列表(0)

  1. 暂无评论