[JS] JSON.stringify 사용시 toJSON() 주의하기
[JS] JSON.stringify 사용시 toJSON() 주의하기
JSON.stringify 사용시 JSON 형태로 바꿀 object가 toJSON 메소드를 정의해서 사용하는 경우,
그 메소드가 대신 불려서 (만약 toJSON() 메소드가 대신 불린다는 사실을 몰랐을 경우)
기대한 결과와 다른 결과 값 때문에 고생할 수 있습니다.
그러므로 toJSON() 메소드를 사용할 때는 항상,
JSON.stringify 에 영향을 줄 수 있다는 사실을 염두해서 사용해야합니다.
----------------------------------------------------------------------------------------------------------------------------------------
toJSON()
작동
If an object being stringified has a property named toJSON
whose value is a function, then the toJSON()
method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON()
method when called will be serialized. For example:
var obj = {
foo: 'foo',
toJSON: function() {
return 'bar';
}
};
JSON.stringify(obj); // '"bar"'
JSON.stringify({ x: obj }); // '{"x":"bar"}'
----------------------------------------------------------------------------------------------------------------------------------------
[출처] https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify