Javascript JSON.stringify 的反转?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11171746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:45:35  来源:igfitidea点击:

Reverse of JSON.stringify?

javascriptjsonobject

提问by thelolcat

I'm stringyfing an object like {'foo': 'bar'}

我正在细化一个对象,例如 {'foo': 'bar'}

How can I turn the string back to an object?

如何将字符串转回对象?

回答by Chase Florell

You need to JSON.parse()the string.

你需要JSON.parse()字符串。

var str = '{"hello":"world"}';
try {
  var obj = JSON.parse(str); // this is how you parse a string into JSON 
  document.body.innerHTML += obj.hello;
} catch (ex) {
  console.error(ex);
}

回答by Niet the Dark Absol

JSON.parseis the opposite of JSON.stringify.

JSON.parse是相反的JSON.stringify

回答by Michael Anderson

JSON.stringifyand JSON.parseare almost oposites, and "usually" this kind of thing will work:

JSON.stringify并且JSON.parse几乎是对立的,并且“通常”这种事情会起作用:

var obj = ...;
var json = JSON.stringify(obj);  
var obj2 = JSON.parse(json);

so that obj and obj2 are "the same".

以便 obj 和 obj2 是“相同的”。

However there are some limitations to be aware of. Often these issues dont matter as you're dealing with simple objects. But I'll illustrate some of them here, using this helper function:

但是,有一些限制需要注意。通常,当您处理简单对象时,这些问题并不重要。但我将在这里说明其中的一些,使用这个辅助函数:

function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
  • You'll only get ownPropertiesof the object and lose prototypes:

    var MyClass = function() { this.foo="foo"; } 
    MyClass.prototype = { bar:"bar" }
    
    var o = new MyClass();
    var oo = jsonrepack(o);
    console.log(oo.bar); // undefined
    console.log( oo instanceof MyClass ); // false
    
  • You'll lose identity:

    var o = {};
    var oo = jsonrepack(o);
    console.log( o === oo ); // false
    
  • Functions dont survive:

    jsonrepack( { f:function(){} } ); // Returns {}
    
  • Date objects end up as strings:

    jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
    
  • Undefined values dont survive:

    var v = { x:undefined }
    console.log("x" in v);              // true
    console.log("x" in jsonrepack(v));  // false
    
  • Objects that provide a toJSONfunction may not behave correctly.

    x = { f:"foo", toJSON:function(){ return "EGAD"; } }
    jsonrepack(x) // Returns 'EGAD'
    
  • 你只会得到ownProperties对象并丢失原型:

    var MyClass = function() { this.foo="foo"; } 
    MyClass.prototype = { bar:"bar" }
    
    var o = new MyClass();
    var oo = jsonrepack(o);
    console.log(oo.bar); // undefined
    console.log( oo instanceof MyClass ); // false
    
  • 你会失去身份:

    var o = {};
    var oo = jsonrepack(o);
    console.log( o === oo ); // false
    
  • 功能不存在:

    jsonrepack( { f:function(){} } ); // Returns {}
    
  • 日期对象以字符串结尾:

    jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
    
  • 未定义的值不存在:

    var v = { x:undefined }
    console.log("x" in v);              // true
    console.log("x" in jsonrepack(v));  // false
    
  • 提供toJSON功能的对象可能无法正确运行。

    x = { f:"foo", toJSON:function(){ return "EGAD"; } }
    jsonrepack(x) // Returns 'EGAD'
    

I'm sure there are issues with other built-in-types too. (All this was tested using node.js so you may get slightly different behaviour depending on your environment too).

我确定其他内置类型也存在问题。(所有这些都是使用 node.js 测试的,因此根据您的环境,您的行为也可能略有不同)。

When it does matter it can sometimes be overcome using the additional parameters of JSON.parseand JSON.stringify. For example:

当它不管它有时可以使用的附加参数来克服JSON.parseJSON.stringify。例如:

function MyClass (v) {
   this.date = new Date(v.year,1,1);
   this.name = "an object";
};

MyClass.prototype.dance = function() {console.log("I'm dancing"); }

var o = new MyClass({year:2010});
var s = JSON.stringify(o);

// Smart unpack function
var o2 = JSON.parse( s, function(k,v){
  if(k==="") { 
     var rv = new MyClass(1990,0,0);
     rv.date = v.date;
     rv.name = v.name;
     return rv
  } else if(k==="date") {
    return new Date( Date.parse(v) );
  } else { return v; } } );

console.log(o);             // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o.constructor); // [Function: MyClass]
o.dance();                  // I'm dancing

console.log(o2);            // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o2.constructor) // [Function: MyClass]        
o2.dance();                 // I'm dancing

回答by Shaik Rasool

http://jsbin.com/tidob/1/edit?js,console,output

http://jsbin.com/tidob/1/edit?js,console,output

The native JSON object includes two key methods.

本机 JSON 对象包括两个关键方法。

1. JSON.parse()
2. JSON.stringify() 
  1. The JSON.parse()method parses a JSON string - i.e. reconstructing the original JavaScript object

    var jsObject = JSON.parse(jsonString);

  2. JSON.stringify() method accepts a JavaScript object and returns its JSON equivalent.

    var jsonString = JSON.stringify(jsObject);

  1. JSON.parse()方法解析一个 JSON 字符串——即重构原始 JavaScript 对象

    var jsObject = JSON.parse(jsonString);

  2. JSON.stringify() 方法接受一个 JavaScript 对象并返回其等效的 JSON。

    var jsonString = JSON.stringify(jsObject);

回答by Mina Gabriel

Recommended is to use JSON.parse

推荐使用 JSON.parse

There is an alternative you can do :

您可以选择另一种方法:

 var myObject = eval('(' + myJSONtext + ')');

Json in javascript

javascript中的Json

Why is using the JavaScript eval function a bad idea?

为什么使用 JavaScript eval 函数是个坏主意?

回答by Exception

How about this

这个怎么样

var parsed = new Function('return ' + stringifiedJSON )();

This is a safer alternative for eval.

对于eval.

var stringifiedJSON = '{"hello":"world"}';
var parsed = new Function('return ' + stringifiedJSON)();
alert(parsed.hello);

回答by Manish Gupta

Check this out.
http://jsfiddle.net/LD55x/

看一下这个。
http://jsfiddle.net/LD55x/

Code:

代码:

var myobj = {};
myobj.name="javascriptisawesome";
myobj.age=25;
myobj.mobile=123456789;
debugger;
var str = JSON.stringify(myobj);
alert(str);
var obj = JSON.parse(str);
alert(obj);

回答by suresh64

$("#save").click(function () {
    debugger
    var xx = [];
    var dd = { "firstname": "", "lastname": "", "address": "" };
    var otable1 = $("#table1").dataTable().fnGetData();

    for (var i = 0; i < otable1.length; i++) {
        dd.firstname = otable1[i][0];
        dd.lastname = otable1[i][1];
        dd.address = otable1[i][2];
        xx.push(dd);
        var dd = { "firstname": "", "lastname": "", "address": "" };
    }
    JSON.stringify(alert(xx));
    $.ajax({

        url: '../Home/save',
        type: 'POST',
        data: JSON.stringify({ u: xx }),
        contentType: 'application/json;',
        dataType: 'json',
        success: function (event) {
            alert(event);
            $("#table2").dataTable().fnDraw();
            location.reload();
        }
    });
});