在JavaScript中使用json.js:使得js数组转为JSON编码

时间:2023-03-24 21:17:44

在json的官网中下载json.js,然后在script中引入,以使用json.js提供的两个关键方法。

1、数组对象.toJSONString()

这个方法将返回一个JSON编码格式的字符串,用来表示类型中的数据。

演示:

<!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>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
function showJsonData(){
original= new Array(0,1,2,3); //在JSON中编码原始值并返回一个字符串
json= original.toJSONString(); div=document.getElementById("jsonData");
div.innerHTML=json;
}
</script>
</head>
<body>
<a href="#" onclick="showJsonData()">Show JSON Data</a>
<div id="jsonData"></div>
</body>
</html>

输出结果:[0,1,2,3]

2、JSON编码.parseJSON()

这个方法可以将JSON编码的字符传恢复为JavaScript结构(如:数组)。

演示:

<!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>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
function showJsonData(){
original= new Array("hgykb","SDHFI"); //在JSON中编码原始值并返回一个字符串
json= original.toJSONString(); div=document.getElementById("jsonData"); //解码JSON数据,并将数组中的第一个元素设置到div.innerHTML属性上
div.innerHTML=json.parseJSON()[0];
}
</script>
</head>
<body>
<a href="#" onclick="showJsonData()">Show JSON Data</a>
<div id="jsonData"></div>
</body>
</html>

输出结果:hgykb