Converts a string to a JSON object.

Source: Internet
Author: User

Most of the time, we need to assemble a string as a JSON object. First, we need to combine the string and then convert it into a JSON object. The following example shows how:

< Script Type = " Text/JavaScript " >
<! --
VaR A = 50 , B = " Xxx " ;
VaR Arr = " {ID: " + A + " , Name :' " + B + " '} " ;
// -->
</ Script >

Combined into the string arr, the next step is to convert it into an object, and soon we will think of using the eval method, but if this conversion will produce an error, today I will try it like this, how can we convert it into a JSON object? After being depressed for a long time, I found a solution in the JSON. js file provided on the JSON official website. The solution is as follows:
Add parentheses at both ends of the string and then the eval will be OK. TestCodeAs follows:

< Script Type = " Text/JavaScript " >
<! --
VaR A = 50 , B = " Xxx " ;
VaR Arr = " {ID: " + A + " , Name :' " + B + " '} " ;
Arr = Eval ('(' + Arr + ')')
Alert (ARR. Name );
// -->
</ Script >

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.