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
Reverse of JSON.stringify?
提问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.parse
is the opposite of JSON.stringify
.
JSON.parse
是相反的JSON.stringify
。
回答by Michael Anderson
JSON.stringify
and JSON.parse
are 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
ownProperties
of 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
toJSON
function 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.parse
and JSON.stringify
. For example:
当它不管它有时可以使用的附加参数来克服JSON.parse
和JSON.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()
The
JSON.parse()
method parses a JSON string - i.e. reconstructing the original JavaScript objectvar jsObject = JSON.parse(jsonString);
JSON.stringify() method accepts a JavaScript object and returns its JSON equivalent.
var jsonString = JSON.stringify(jsObject);
该
JSON.parse()
方法解析一个 JSON 字符串——即重构原始 JavaScript 对象var jsObject = JSON.parse(jsonString);
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 + ')');
回答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();
}
});
});