programing

JSON.stringify의 역방향?

goodcopy 2022. 10. 27. 22:03
반응형

JSON.stringify의 역방향?

난 물건을 꽉 잡고 있어{'foo': 'bar'}

스트링을 오브젝트로 되돌리려면 어떻게 해야 하나요?

유효한 JSON 문자열이 필요합니다.

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

JSON.parse와는 정반대이다JSON.stringify.

JSON.stringify그리고.JSON.parseoposite에 가깝기 때문에 "보통" 이런 종류의 작업이 작동합니다.

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

obj와 obj2가 "같은" 상태가 되도록 합니다.

그러나 몇 가지 제한 사항이 있습니다.단순한 오브젝트를 취급하고 있기 때문에, 이러한 문제는 문제가 되지 않는 경우가 많습니다.여기에서는, 다음의 헬퍼 기능을 사용해 몇개의 예를 나타냅니다.

function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
  • 얻을 수 있는 것은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'
    

다른 빌트인 타입에도 문제가 있다고 생각합니다.(이 모든 것은 node.js를 사용하여 테스트되었기 때문에 환경에 따라 동작이 약간 다를 수 있습니다.)

이것이 중요한 경우에는 다음과 같은 추가 파라미터를 사용하여 극복할 수 있습니다.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

를 사용하는 것이 좋습니다.JSON.parse

다른 방법이 있습니다.

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

javascript의 Json

왜 JavaScript 평가 기능을 사용하는 것이 나쁜 생각일까요?

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

네이티브 JSON 오브젝트에는 2개의 주요 메서드가 있습니다.

1. JSON.parse()
2. JSON.stringify() 
  1. JSON.parse()메서드는 JSON 문자열을 해석합니다.즉, 원래 JavaScript 개체를 재구성합니다.

    var jsObject = JSON.parse(jsonString);

  2. JSON.stringify() 메서드는 JavaScript 객체를 받아들여 대응하는 JSON을 반환합니다.

    var jsonString = JSON.stringify(jsObject);

이건 어때?

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

이것은 에 대해 보다 안전한 대안이다.eval.

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

이것 좀 봐.
http://jsfiddle.net/LD55x/

코드:

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

이 부분적인 해결책은 어떻습니까?

플로우상의 많은 함수 노드에서 사용되는 data + 메서드(외부 라이브러리 Import의 대체 수단)와 함께 글로벌 bigobj를 저장(Config 노드 사용)하고 싶다.

이상하지만 작동:글로벌 변수 'bigobj':

{
some[]more[]{dx:"here"} , // array of objects with  array of objects. The 'Config' node requires JSON.
.....
 "get_dx": "function( d,p) {  return this.some[d].more[p].dx; }"  // test function
}

즉, 함수의 JSON 버전... (모두 한 줄에 있음: ( )

용도: 기능 노드 내부:

var bigO = global.get("bigobj");

function callJSONMethod(obj, fname, a, b, c, d){
    // see: https://stackoverflow.com/questions/49125059/how-to-pass-parameters-to-an-eval-based-function-injavascript
var wrap = s => "{ return " + obj[fname] + " };" //return the block having function expression
var func = new Function(wrap(obj[fname]));
return func.call( null ).call( obj, a, b, c, d); //invoke the function using arguments
}

msg.payload =callJSONMethod(bigO, "get_dx", 2, 2); 
return msg:

"여기"를 반환한다, 믿을 수 없다!

즉, 함수 callJ를 추가해야 합니다.SONMethod()는 bigobj.....를 사용하여 모든 함수 블록에 적용할 수 있습니다.

안부 전합니다

언급URL : https://stackoverflow.com/questions/11171746/reverse-of-json-stringify

반응형