Home  >  Article  >  Backend Development  >  Three ways to convert strings to json format in js

Three ways to convert strings to json format in js

WBOY
WBOYOriginal
2016-07-25 09:02:58827browse
  1. function strToJson(str){
  2. var json = eval_r('(' + str + ')');
  3. return json;
  4. }?>
Copy code

Don’t forget the parentheses on both sides of str. Method two, new Function form

  1. function strToJson(str){
  2. var json = (new Function("return " + str))();
  3. return json;
  4. }?>
Copy code

Method 3, use global JSON object

  1. function strToJson(str){
  2. return JSON.parse(str);
  3. }?>
Copy code

Currently in IE8(S)/Firefox3.5+ /Chrome4/Safari4/Opera10 has implemented this method.

When using JSON.parse, you must strictly abide by the JSON specification. For example, attributes need to be enclosed in quotation marks, as follows: var str = '{name:"jack"}'; var obj = JSON.parse(str); // --> parse error The name is not enclosed in quotes. When using JSON.parse, an exception is thrown in all browsers and the parsing fails. The first two methods are fine.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn