jQuery loop over JSON string $.each example

摘要: Review a simple jQuery example to loop over a JavaScript array object.

Review a simple jQuery example to loop over a JavaScript array object.

var json = [
	{"id":"1","tagName":"apple"},
	{"id":"2","tagName":"orange"},
	{"id":"3","tagName":"banana"},
	{"id":"4","tagName":"watermelon"},
	{"id":"5","tagName":"pineapple"}
];
$.each(json, function(idx, obj) {
	alert(obj.tagName);
});

Above code snippet is working fine, prompts the “apple”, “orange” … as expected.

Problem : JSON string

Review below example, declares a JSON string (enclosed with single or double quotes) directly.

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';
$.each(json, function(idx, obj) {
	alert(obj.tagName);
});

In Chrome, it shows following errors in console :

Uncaught TypeError: Cannot use 'in' operator to search for '156' 
in [{"id":"1","tagName":"apple"}...

Solution : Convert JSON string to JavaScript object

To fix it, converts it to Javascript object via standard JSON.parse() or jQuery $.parseJSON.

var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';
$.each(JSON.parse(json), function(idx, obj) {
	alert(obj.tagName);
});
//or 
$.each($.parseJSON(json), function(idx, obj) {
	alert(obj.tagName);
});
Note
Most web applications will return JSON formatted string directly, you need to convert it to JavaScript object before parse it with jQuery.

References

  1. jQuery $each() example
  2. Wikipedia : JSON

上一篇: Spring Data MongoDB : like query example
下一篇: How to access JSON object in JavaScript
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号