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

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