Introduction to the method of converting a string into a JSON object by JS

Source: Internet
Author: User
Tags eval json tojson

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

Example 1

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>

2,new function form, more bizarre Oh. As follows

The code is as follows Copy Code

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

3, use the global JSON object as follows:

The code is as follows Copy Code

function Strtojson (str) {
return Json.parse (str);
}

The following two conversion methods are recommended for personal use Oh, this relatively secure method, especially json.parse, converts strings to objects.

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.