Conversion between json objects and string objects in JavaScript

Source: Internet
Author: User

Json object
Copy codeThe Code is as follows:
Var json = {aa: true, bb: true };
Var json1 = {aa: 'B', bb: {cc: true, dd: true }};

1: js json object operation
Copy codeThe Code is as follows:
For (var item in json ){
Alert (item); // The result is aa, bb, And the type is string.
Alert (typeof (item ));
Alert (eval ("json." + item); // The result is true, and the true type is boolean.
Eval ("json." + item + "= false;"); // change the value of the json object
}

2: how to convert a json object to a String object
Copy codeThe Code is as follows:
/**
* Convert a json object to a string
*/
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 a string object to a json object
Copy codeThe Code is as follows:
Function stringToJson (stringValue)
{
Eval ("var theJsonValue =" + stringValue );
Return theJsonValue;
}

4: Method for converting a json array to a String object (to remove the method above)
Copy codeThe 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 json. js json to convert string
Copy codeThe 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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.