JSON和Object数组在js中的转换
<span style="font-size:14px;"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JSON test</title> <script> /* * JSON对于javascript来讲就相当于一个对象或者包含多个对象的list */ window.onload = function() { var json_array = new Array(); for(var i = 0;i<10;i++) { /* * 创建object对象,存放到数组中 */ var person ={}; person.name = "Q"+i; person.age = i; json_array.push(person); } /* * 将object数组转会为json形式; */ var json = JSON.stringify(json_array); console.log(json); /* * json转object数组 */ var jsonobj = JSON.parse(json, function (key, value) { return key.indexOf('date') >= 0 ? new Date(value) : value; }); console.log(jsonobj); } </script> </head> <body> </body> </html> </span>
控制台打印结果:
[{"name":"Q0","age":0},{"name":"Q1","age":1},{"name":"Q2","age":2},{"name":"Q3","age":3},{"name":"Q4","age":4},{"name":"Q5","age":5},{"name":"Q6","age":6},{"name":"Q7","age":7},{"name":"Q8","age":8},{"name":"Q9","age":9}]
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]