反向JSON.stringify?

本文翻译自:Reverse of JSON.stringify?

I'm stringyfing an object like {'foo': 'bar'} 我正在像{'foo': 'bar'}这样的对象。

How can I turn the string back to an object? 如何将字符串转回对象?


#1楼

参考:https://stackoom.com/question/ksHS/反向JSON-stringify


#2楼

JSON.parseJSON.stringify相反。


#3楼

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); } 


#4楼

JSON.stringify and JSON.parse are almost oposites, and "usually" this kind of thing will work: JSON.stringifyJSON.parse几乎是JSON.stringify ,“通常”这种事情会起作用:

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: 您将只获得该对象的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 
  • 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. 提供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 . 当它确实重要时,有时可以使用JSON.parseJSON.stringify的附加参数来克服它。 For example: 例如:

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

#5楼

Recommended is to use JSON.parse 建议使用JSON.parse

There is an alternative you can do : 您可以选择其他方法:

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

Json in javascript Json在javascript中

Why is using the JavaScript eval function a bad idea? 为什么使用JavaScript eval函数是一个坏主意?


#6楼

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); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章