JS processing for converting JSON data into Data Objects

Source: Internet
Author: User

During data transmission,JSONIt is transmitted in the form of text, that is, strings, andJSThe operation isJSONObject, so,JSONObject andJSONMutual conversion between strings is the key. For example:

JSONString:

VaR str1 = '{"name": "cxh", "sex": "Man "}';

JSONObject:

VaR str2 = {"name": "cxh", "sex": "Man "};

 

I,JSONConvert stringJSONObject

To useStr1, You must first convertJSONObject:

//ByJSONConvert stringJSONObject

VaR OBJ = eval ('+ STR + ')');

Or

VaR OBJ = Str. parsejson ();//ByJSONConvert stringJSONObject

Or

VaR OBJ = JSON. parse (STR );//ByJSONConvert stringJSONObject

Then, you can read:

Alert (obj. Name );

Alert (obj. Sex );

NOTE: IfOBJIsJSONObject, then useEval() After Function Conversion (even Multiple conversions) orJSONObject, but useParsejson() There will be a problem after the function is processed (a syntax exception is thrown ).


II,JSONConvert objectsJSONString

AvailableTojsonstring ()Or Global MethodJSON. stringify ()SetJSONObject conversionJSONString.

For example:

VaR last = obj. tojsonstring ();//SetJSONObject conversionJSONCharacter

Or

VaR last = JSON. stringify (OBJ );//SetJSONObject conversionJSONCharacter

Alert (last );

 

Note:

Among the methods above, Eval () Function is JS Other methods come from JSON. js Package. New Version JSON Modified API , Set JSON. stringify () And JSON. parse () Both methods are injected Javascript In the built-in object, the former becomes Object. tojsonstring () And the latter becomes String. parsejson () . If the prompt is not found Tojsonstring () And Parsejson () Method, it indicates your JSON The package version is too low.

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.