Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JSON.stringify recognize properties defined with Object.defineProperty?

Tags:

javascript

Does JSON.stringify work with objects that are created like

obj = {}
Object.defineProperty(obj, 'prop', {
  get: function() { return 1 }
  set: function(value) { ... }
})

It returns {} when called on this object.

like image 275
user2032804 Avatar asked Mar 30 '13 00:03

user2032804


People also ask

Does JSON Stringify work on objects?

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Can you JSON Stringify an array of objects?

The JSON. stringify method converts a JavaScript object or value to a JSON string. It can optionally modify or filter values if a replacer function/array is specified.

When should I use JSON Stringify?

The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.

What is JSON Stringify and JSON parse?

parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string. Follow this answer to receive notifications.

What does JSON stringify () do?

JSON.stringify () calls toJSON with one parameter: if this object is a property value, the property name if it is in an array, the index in the array, as a string an empty string if JSON.stringify () was directly called on this object

What is the use of object defineproperty () method in Java?

The static method Object.defineProperty () defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

Why does JSON stringify throw a TypeError?

Like JSON.parse (), JSON.stringify () may throw errors, so it should be wrapped in a try catch statement. The function throws a TypeError in two contexts: if a circular reference occurs in the Javascript object or if the Javascript object contains a BigInt.

What are non-enumerable properties in JSON?

In the context of JSON.stringify (), non-enumerable properties are those that you can convert into a string without losing important contextual information.


1 Answers

You might want to set the enumerable option to true, like this:

Object.defineProperty(o, 'test', {
    get: function () { return 1; },
    enumerable: true
});
like image 127
plalx Avatar answered Oct 20 '22 19:10

plalx