<!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=gb2312" />
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(
function(){
var json = {"name":"Mike","sex":"女","age":29};
alert(typeof json);
var temp = obj2str(json);
alert(temp);
alert(typeof temp);
}
);
//下面这个方法是将json对象转换为字符串
function obj2str(o){
var r = [];
if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
if(typeof o =="undefined") return "undefined";
if(typeof o == "object"){
if(o===null) return "null";
else if(!o.sort){
for(var i in o)
r.push(i+":"+obj2str(o[i]))
r="{"+r.join()+"}"
}else{
for(var i =0;i<o.length;i++)
r.push(obj2str(o[i]))
r="["+r.join()+"]"
}
return r;
}
return o.toString();
}
/*使用jquery插件,需要注意的是json的key-value必须都为字符串,即都需要使用双引号包起来,
不能使用单引号,如果value是数字就不需要用双引号包起来*/
function jquery_string_to_json(){
var jsonString = '{"name":"huangbiao","sex":"boy","age":16}';
//var jsonString = "{'name':'huangbiao','sex':'boy','age':16}";//错误的声明
alert(typeof jsonString);
var obj = jQuery.parseJSON(jsonString);
alert(typeof obj);
}
/*使用eval方法对于字符串里面的key-value都必须使用双引号括起来,不能使用单引号,否则不
能够正常解析*/
function String_to_JSON(){
var json = '{"name":"huangbiao","sex":"boy","age":16}';
var temp = eval('('+json+')');//eval方法里面的括号是不能够少的,否则报脚本错误
alert(typeof temp);
alert(temp.name);
//使用JSON对象只能在IE8以上的版本支持,因此不建议使用这种方式转换
//var json = '{"name":"Mike","sex":"女","age":"29"}';
//var temp = JSON.parse(json);
//alert(temp.name);
}
</script>
<title>无标题文档</title>
</head>
<body>
</body>
</html>
function obj2str(o){
var r = [];
if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
if(typeof o =="undefined") return "undefined";
if(typeof o == "object"){
if(o===null) return "null";
else if(!o.sort){
for(var i in o)
r.push(i+":"+obj2str(o[i]))
r="{"+r.join()+"}"
}else{
for(var i =0;i<o.length;i++)
r.push(obj2str(o[i]))
r="["+r.join()+"]"
}
return r;
}
return o.toString();
}
function json2obj(o){
var result = obj2str(o);
return eval("(" + result + ")");
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有