js中json对象和string互转

json转string的方法

/** 
			* json对象转字符串形式 
			*/ 
			function json2str(o) { 
			var arr = []; 
			var fmt = function(s) { 
			if (typeof s == 'object' && s != null) return json2str(s); 
			return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s; 
			} 
			for (var i in o) arr.push("'" + i + "':" + fmt(o[i])); 
			return '{' + arr.join(',') + '}'; 
			} 

string转json的方法

function stringToJson(stringValue) 
{ 
eval("var theJsonValue = "+stringValue); 
return theJsonValue; 
} 

如果是前台数据要拼接为json对象向后台或其他地方发送。可以用我之前写的文章里的方法,以前遇到过这种问题,记录在 js实现获取页面数据转为Json数据并使用

json转string的例子

<!DOCTYPE html >
<html > 
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<input type="button" value="click" onclick="clickMe()" />
		<script type="text/javascript">
			var w = {a:"A",b:"B",c:"C"};
			function clickMe(){
				w = json2str(w);
				alert(typeof(w));
				console.log(w);
			}
			/** 
			* json对象转字符串形式 
			*/ 
			function json2str(o) { 
			var arr = []; 
			var fmt = function(s) { 
			if (typeof s == 'object' && s != null) return json2str(s); 
			return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s; 
			} 
			for (var i in o) arr.push("'" + i + "':" + fmt(o[i])); 
			return '{' + arr.join(',') + '}'; 
			} 
		</script>
	</body>
</html>
实现结果如下




猜你喜欢

转载自blog.csdn.net/HGJacky/article/details/78199926