Home >Web Front-end >JS Tutorial >Detailed example of how to convert json and string into each other in JavaScript

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

伊谢尔伦
伊谢尔伦Original
2017-07-26 11:13:202175browse

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对象的值 
}

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(',') + '}'; 
}

3: Convert string object to json object

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

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; 
}

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>


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!

Statement:
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