这篇文章主要讲解:json结构及形式、json字符串转化为json对象【通过eval( ) 方法,new Function形式,使用全局的JSON对象】、json校验格式化工具简单实现
一.json结构及形式
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
[
{
key1:value1,
key2:value2
},
{
key3:value3,
key4:value4
}
]
二.json字符串转化为json对象
var json_text = "{'book':{'name':'JAVA编程','author':['Liu','Xu']},'num':222}";
<script type="text/javascript">
window.onload = function(){
var json_text = "{'book':{'name':'JAVA编程','author':['Liu','Xu']},'num':222}";
//使用eval()将字符串转换为对象
var json_obj = eval("("+ json_text +")");
//访问 book-name
document.write(json_obj.book.name);
//访问 book-author-Xu
document.write(json_obj.book.author[1]);
}
</script>
<script type="text/javascript">
window.onload = function(){
var json_text = "{'book':{'name':'JAVA编程','author':['Liu','Xu']},'num':222}";
//用new Function将字符串转换为对象
var json_obj = (new Function("return" + json_text))();
//访问 book-name
document.write(json_obj.book.name);
//访问 book-author-Xu
document.write(json_obj.book.author[1]);
}
</script>
<script type="text/javascript">
window.onload = function(){
var json_text = '{"book":"js"}';
//用全局JSON将字符串json转换为json对象
var json_obj = JSON.parse(json_text);
//访问 book-name
document.write(json_obj.book);
//访问 book-author-Xu
//document.write(json_obj.book.author[1]);
}
</script>
三.json校验格式化工具简单实现
<body>
<textarea id="content_value">
</textarea>
<input type="button" value="格式化" onclick="check()">
<textarea id="output_value">
</textarea>
</body>
<script type="text/javascript">
function check(){
var text_value = document.getElementById('content_value').value;
if(text_value == ""){
alert("不能为空");
return false;
} else {
var res="";
for(var i=0,j=0,k=0,ii,ele;i<text_value.length;i++)
{//k:缩进,j:""个数
ele=text_value.charAt(i);
if(j%2==0&&ele=="}")
{
k--;
for(ii=0;ii<k;ii++) ele=" "+ele;
ele="\n"+ele;
}
else if(j%2==0&&ele=="{")
{
ele+="\n";
k++;
debugger;
for(ii=0;ii<k;ii++) ele+=" ";
}
else if(j%2==0&&ele==",")
{
ele+="\n";
for(ii=0;ii<k;ii++) ele+=" ";
}
else if(ele=="\"") j++;
res+=ele;
}
document.getElementById('output_value').value = res;
}
}
</script>