-1

JSON.stringify(data) is removing certain of data

Tried the below resolution but it did not work either

const obj = {
  prop1: 'value1'
};

Object.defineProperty(obj, 'prop2', {
  value: 'value2',
  enumerable: false
});

console.log(JSON.stringify(obj));

Is there a way to stop JSON.stringify from removing extracts of data ?

3
  • 3
    If a property is not enumerable, how do you expect JSON.stringify to find it? JSON.stringify is not meant to produce a perfect replica of all possible JavaScript objects. In fact it's intentionally restricted to a subset of JavaScript to be easily transferrable. Commented Oct 18, 2023 at 10:13
  • This is by design. JSON.stringify only includes own, enumerable properties with string keys, not other kinds of properties (inherited, non-enumerable, properties with Symbol keys). In your example, the property being omitted is non-enumerable, so it's not included. Commented Oct 18, 2023 at 10:17
  • JSON as said is a restricted kind of Javascript Object notation, so even JSON.stringify({x:undefined}) will do something you might not expect. Commented Oct 18, 2023 at 10:26

2 Answers 2

0

enumerable false makes your property transparent to some functionalities. Try setting it to true.

Sign up to request clarification or add additional context in comments.

Comments

0

It is explicitly documented that when using JSON.stringify:

Only enumerable own properties are visited.

You've set the property to enumerable: false so it won't be included.

You can't change that behaviour of JSON.stringify. You could change your property definition.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.