Conversion between a JSON object and a string object in Javascript

Source: Internet
Author: User

JSON object
VaR JSON = {AA: True, BB: true };
VaR json1 = {AA: 'B', BB: {CC: True, DD: true }};
1: js json object operation
For (VAR item in JSON ){
Alert (item); // The result is AA, BB, And the type is string.
Alert (typeof (item ));
Alert (EV Al ("JSON." + item); // The result is true, and the true type is boolean.
EV Al ("JSON." + item + "= false;"); // change the value of the JSON object
}

2: how to convert a JSON object to a string object
1 /* *
2 * Convert a JSON object to a string
3 */
4 Function Json2str (o ){
5 VaR Arr = [];
6 VaR FMT =   Function (S ){
7 If ( Typeof S =   ' Object '   && S ! =   Null ) Return Json2str (s );
8 Return   / ^ (String | Number) $ / . Test ( Typeof S) ?   " ' "   + S +   " ' " : S;
9 }
10 For ( VaR I In O) Arr. Push ( " ' "   + I +   " ': "   + FMT (O [I]);
11 Return   ' { '   + Arr. Join ( ' , ' ) +   ' } ' ;
12 }
3: convert a String object to a JSON object
Function stringtojson (stringvalue)
{
EV Al ("Var thejsonvalue =" + stringvalue );
Return thejsonvalue;
}

4: Method for converting a JSON array to a string object (to remove the method above)
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


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.