Technologies:
Tolerim
24 days ago
How can JSON.stringify produce inconsistent results between the console and Firebase Cloud Function?
const list = [{
value1: 'one',
value2: 'two',
value3: 'three',
}]
docRef.update({ list: JSON.stringify(list) })
// As a result of this code,
// '[{"value1":"one","value2":"two","value3":"three"},{}]' is being written to firestore.
// If you perform the JSON.stringify(list) function in Chrome Dev Console,
// you will obtain the anticipated '[{"value1":"one","value2":"two","value3":"three"}]'.
{}
appearing in the Node environment?Answers(2)
Vogi
24 days ago
Verified Answer
The reason behind the additional {} appearing in the Node environment is that JSON.stringify includes an object's own, enumerable properties that have values that aren't functions or undefined (as JSON doesn't have those), leaving out ones it inherits from its prototype, any that are defined as non-enumerable, and any whose value is a function reference or undefined.
In this case, the object in question is an array with one element. The array has one property which is an object with three properties. When you call JSON.stringify on this array, it will include the enumerable properties of the object in the array but not the inherited properties. Since there are no inherited properties in this case, JSON.stringify will only include the enumerable properties of the object which are value1, value2, and value3.
When you call JSON.stringify on this array in Chrome Dev Console, you will obtain the anticipated '[{"value1":"one","value2":"two","value3":"three"}]' because Chrome Dev Console does not include inherited properties.
I hope this helps!
Sources
JSON.stringify() - JavaScript | MDN - Mozilla Developerjavascript - Why does JSON.stringify return empty object notation ...How to fix JSON stringify returning an empty object?How to send JSON response using Node.jsHow to fix JSON.stringify returning an empty objectTolerim
24 days ago
The issue appears to be related to the fact that in the Node environment, the list array is being treated as an array with two elements - the first being the object with keys value1, value2, and value3, and the second being undefined.
To avoid this issue, you could try removing the square brackets around the object in the list array, like this:
const list = {
value1: 'one',
value2: 'two',
value3: 'three',
};
docRef.update({ list: JSON.stringify(list) });
This should result in the expected output of {"value1":"one","value2":"two","value3":"three"} being written to Firestore.