Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The json object and the string object in JavaScript transform each other


May 08, 2021 JSON


Table of contents


JSON: JavaScript Object Notation, in fact, JSON is just a JavaScript object.

json object

The code is as follows:
var json = {aa:true,bb:true}; 
var json1 = {aa:'b',bb:{cc:true,dd:true}}; 

1:js manipulates the json object

The code is as follows:
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: The method by which the json object is converted into a String object

The code is as follows:
/** 
* 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: The string object is converted to a johnson object

The code is as follows:
function stringToJson(stringValue) 
{ 
eval("var theJsonValue = "+stringValue); 
return theJsonValue; 
} 

4: The method by which the json array is converted into a String object (to drop the method above)

The code is as follows:
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 the .js json to turn string

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

Create a new string (JSON text) in javascript.

var txt = '{ "employees" : [' +
'{ "firstName":"Bill" , "lastName":"Gates" },' +
'{ "firstName":"George" , "lastName":"Bush" },' +
'{ "firstName":"Thomas" , "lastName":"Carter" } ]}'; 

Because the JSON syntax is a subset of the JavaScript syntax, the JavaScript function eval() can be used to convert JSON text to JavaScript objects.

The eval() function uses a JavaScript compiler that parses JSON text and then generates JavaScript objects. The text must be surrounded in parentheses to avoid syntax errors:

var obj = eval ("(" + txt + ")"); 

Note: The eval() function compiles and executes any JavaScript code. This hides a potential security issue.

Using the JSON parser to convert JSON to JavaScript objects is more secure. The JSON parser recognizes only JSON text, not compiles scripts.

In the browser, this provides native JSON support, and the JSON parser is faster.

Native support for JSON is included in the newer browsers and the latest ECMAScript (JavaScript) standards.

String to jason object: JSON.parse (jsonstr);

json object to jason string: JSON.stringify (jsonObj);

JQuery method:

json string to jason object: jQuery.parseJSON (jsonStr);

<html>
<body>
<h2>通过 JSON 字符串来创建对象</h3>
<p>
First Name: <span id="fname"></span><br /> 
Last Name: <span id="lname"></span><br /> 
</p> 
<script type="text/javascript">
var txt = '{"employees":[' +
'{"firstName":"Bill","lastName":"Gates" },' +
'{"firstName":"George","lastName":"Bush" },' +
'{"firstName":"Thomas","lastName":"Carter" }]}';
obj = JSON.parse(txt);
document.getElementById("fname").innerHTML=obj.employees[1].firstName 
document.getElementById("lname").innerHTML=obj.employees[1].lastName 
</script>
</body>
</html> 


So how do you traverse the jason array? You can treat it as a normal javascript object.

<html>
<body>
<h2>如何遍历JSON数组</h3>
<div id="result"></div>
<script type="text/javascript">
var txt = '[{"firstName":"Bill","lastName":"Gates" },' +
'{"firstName":"George","lastName":"Bush" },' +
'{"firstName":"Thomas","lastName":"Carter" }]';
var arrayJson = JSON.parse(txt);
var html='';
for(var p in arrayJson){
html+=' firstName:'+arrayJson[p].firstName;
html+=' lastName'+arrayJson[p].lastName;
html+='<br />';
}
document.getElementById("result").innerHTML= html;
</script>
</body>
</html> 

ie8 (compatible mode), ie7 and ie6 do not have JSON objects, but http://www.json.org/js.html provides a json .js so that ie8 (compatible mode), ie7 and ie6 can support Json objects as well as its https://github.com/douglascrockford/JSON-js stringify() and parse(.js) methods;

ie8 (compatible mode), ie7 and ie6 can use eval() to convert strings to JSON objects,

var c='{"name":"Mike","sex":"女","age":"29"}';
var cToObj=eval("("+c+")");
alert(typeof(cToObj));