Home > Article > Web Front-end > Detailed example of how to convert json and string into each other in JavaScript
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!