Home >Web Front-end >JS Tutorial >Why Does JSON.stringify Return an Empty Object When Stringifying Native Error Objects?
In the realm of web development, the JSON.stringify function is a powerful tool for converting JavaScript objects into JSON strings. However, an unusual behavior arises when attempting to stringify native Error objects. Instead of the expected error information, an empty object is returned.
To delve into this phenomenon, consider the following code snippet:
const error = new Error('simple error message'); console.log(JSON.stringify(error)); // Outputs: '{}'
As demonstrated above, JSON.stringify returns an empty object, suggesting that the native Error object's properties are not stringified. This behavior stems from the lack of enumerable properties in Error objects.
To verify this, we can use Object.getOwnPropertyNames to retrieve the names of the properties defined in an Error object:
console.log(Object.getOwnPropertyNames(error)); // Outputs: ['stack', 'arguments', 'type', 'message']
However, if we inspect the property descriptors, we find that the enumerable attribute is set to false for all properties:
for (var property in error) { var descriptor = Object.getOwnPropertyDescriptor(error, property); console.log(property, descriptor); }
Despite the lack of enumerable properties, there exists a workaround to stringify native Error objects using JSON.stringify:
JSON.stringify(err, Object.getOwnPropertyNames(err))
By providing the list of property names as the second argument to JSON.stringify, we explicitly instruct it to include them in the stringification process, even though they are not enumerable by default.
The above is the detailed content of Why Does JSON.stringify Return an Empty Object When Stringifying Native Error Objects?. For more information, please follow other related articles on the PHP Chinese website!