Three ways to convert a string to JSON format in JS

Source: Internet
Author: User
Tags string to json
  1. !--? php function Strtojson (str) {
  2. var json = Eval_r (' (' + str + ') ');
  3. return JSON;
  4. }?>
copy code

The parentheses on both sides of Str do not forget. Method two, new function form

  1. !--? php function Strtojson (str) {
  2. var json = (new Function ("return" + str)) ();
  3. return JSON;
  4. }?>
copy code

Method Three, using global JSON objects

  1. !--? php function Strtojson (str) {
  2. return json.parse (str);
  3. }?>
copy code

Currently in IE8 (S)/firefox3.5+/chrome4/safari4/ OPERA10 has implemented this method. The

uses json.parse strict adherence to the JSON specification, such as the attribute is enclosed in quotation marks, as follows: var str = ' {name: ' Jack '} '; var obj = Json.parse (str);//--Parse ErrorName is not enclosed in quotation marks, the parsing fails with the exception thrown by all browsers using Json.parse. And the first two ways are fine.

  • Related Article

    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.