在JAVASCRIPT中构建一个复杂的对象,并用JSON进行转换

时间:2022-03-07 23:45:10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>试卷预览</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <script type="text/javascript" src="json2.js"></script>
<script>
var o=new Object();
o.title="黄海测试";
o.h2_l="副标题"; o.ti=new Array();
o.ti[]=new Object();
o.ti[].t_id="06A14600-6AA7-4A45-9DCD-842D3EE6C53B";
o.ti[].t_title="东师理想"; o.ti[]=new Object();
o.ti[].t_id="08A02A35-3208-4543-ACD8-EE9F336C3DB0";
o.ti[].t_title="东师理想"; o.ti[]=new Object();
o.ti[].t_id="3E04A1B8-D820-4EB3-9568-E4A034628DC1";
o.ti[].t_title="东师理想"; console.log(o); //类似于CJSON库
console.log(JSON.stringify(o));
</script> </head>
<html>
<body></body>
</html>

进行JSON解析和转换的类库地址:

https://codeload.github.com/douglascrockford/JSON-js/zip/master

在页面中添加json2.js的引用。

<script type="text/javascript" src="/CoreResource/JS/json2.min.js"></script>

序列化方法

var jsonObj = { id: '', name: 'Tom' };
JSON.stringify(jsonObj); 反序列化方法 var jsonString = "{ id: '01', name: 'Tom' }";
JSON.parse(jsonString);