Home  >  Article  >  Web Front-end  >  Conversion between json objects and string objects in JavaScript_javascript skills

Conversion between json objects and string objects in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:45:291259browse
json object
Copy code The code is as follows:

var json = { aa:true,bb:true};
var json1 = {aa:'b',bb:{cc:true,dd:true}};

1: js Manipulate json object
Copy code The code is as follows:

for(var item in json ){
alert(item); //The result is aa, bb, the type is string
alert(typeof(item));
alert(eval("json." item)); //The result is true, the true type is boolean
eval(("json." item "=false;")); //Change the value of the json object
}

2 : Method to convert json object into String object
Copy code The code is as follows:

/**
* json object to string format
*/
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
Copy code The code is as follows :

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

4: Method to convert json array into String object (requires the above method)
Copy code The code is as follows:

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

5: Use json.js json to string
Copy code Code As follows:


<script> <br>var date = {myArr : ["a" , " b" , "c" , "d"] , count : 4}; <br>var str = JSON.stringify(date); <br>alert(str); <br></script>
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