Several ways to convert a JS string into a JSON object

Source: Internet
Author: User
Tags eval json tojson

Instance one,

In JS, the JSON-formatted string is converted to a JSON object, and the key code

The code is as follows Copy Code

JSON = eval (' (' +str+ ') ');

The method is as follows:

The code is as follows Copy Code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>json Application </title>
<script type= "Text/javascript" >
function Strtojson (str) {
JSON = eval (' (' +str+ ') ');
return JSON;
}
function Tojson (data) {
JSON = eval (data);
return JSON;
}

JSON data
str = ' {id:1,title: Hello, friend ', Addtime: ' 2010-05-03 '} ';
Strjson = Strtojson (str);
data = {id:2,title: "Hello, haha", addtime: "2010-05-04"};
Json = Tojson (data);

document.write (strjson.id+ "," +strjson.title+ "" +strjson.addtime+ "<br/>");
document.write (json.id+ "," +json.title+ "" +json.addtime+ "<br/>");
</script>
<body>
</body>

Example 2

Using the new function form

The code is as follows Copy Code

function Strtojson (str) {
var json = (new Function ("return" + str)) ();
return JSON;
}

Example 3, using the relevant Json2 plug-in example

  code is as follows copy code

 

<script src=" ... /jquery/jquery-1.5.2.min.js "type=" Text/javascript "></SCRIPT>
    <script src=". /json2.js "type=" Text/javascript ></script>
        var a = ' {' name ' : "Tom", "Sex": "Male", "Age": "a";   //String used to compose JSON;
        alert ("string used to compose JSON:" "+a+" "");
        var b = Json2.parse (a);  //convert string A to JSON format B
         var c = json2.stringify (a); Converts JSON format B to string C
        alert ("Converted string:" "+c+" "");

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.