Home > Web Front-end > JS Tutorial > body text

Detailed example of how to convert json and string into each other in JavaScript

伊谢尔伦
Release: 2017-07-26 11:13:20
Original
2153 people have browsed it

1: js operates json object

for(var item in json){ 
alert(item); //结果是 aa,bb, 类型是 string 
alert(typeof(item)); 
alert(eval("json."+item)); //结果是true,true类型是boolean 
eval(("json."+item+"=false;")); //改变json对象的值 
}
Copy after login

2: Method to convert json object into String object

/** 
* 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(',') + '}'; 
}
Copy after login

3: Convert string object to json object

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

4: Method to convert json array into String object (requires the above method)

function JsonArrayToStringCfz(jsonArray) 
var JsonArrayString = "["; 
for(var i=0;i<jsonArray.length;i++){ 
JsonArrayString=JsonArrayString+JsonToStringCfz(jsonArray[i])+","; 
} 
JsonArrayString = JsonArrayString.substring(0,JsonArrayString.length-1)+"]"; 
return JsonArrayString; 
}
Copy after login

5: Use json.js json to string

<script src="json2.js"></script> 
<script> 
var date = {myArr : ["a" , "b" , "c" , "d"] , count : 4}; 
var str = JSON.stringify(date); 
alert(str); 
</script>
Copy after login


The above is the detailed content of Detailed example of how to convert json and string into each other in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!