0

I have this object:

{
   exports: class y {}
}

Now I'm doing JSON.stringify on it:

JSON.stringify({
    exports: class y {}
})

But it returns an empty object... What did I do wrong? Thanks

4
  • What did you want the output to be? Commented Mar 24, 2019 at 13:55
  • something like "{"exports": class y {}}" Commented Mar 24, 2019 at 13:55
  • JSON was standardized long before JavaScript had class syntax, so that would be invalid JSON. You can read the spec for JSON at json.org Commented Mar 24, 2019 at 13:58
  • 1
    "A value can be a string in double quotes, or a number, or true or false or null, or an object or an array" json.org Commented Mar 24, 2019 at 14:05

1 Answer 1

3

a class is actually a function without a [[call]] internal property. This type does not have a representation in JSON, hence the result you see. You can try to JSON.stringify objects containing function to see the same result.

As a rule of thumb you should never try to store code as data in JS. Storing code is hard and requires you to store lots of information about the code but also about the state of the environment. Look at babel and its api as an example of manipulating code as data.

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

5 Comments

So what should I do?
Tell us what you actually want to do would be a good start. Classes cannot be represented in JSON, so if that is the actual question the answer is that it isn't possible.
You need to provide a value of a type that have a valid representation in JSON. Those can be objects, arrays, strings, number, boolean and null. Other types when present as the value of a field will make the field being ignored when serializing the structure into a json string. Why are you trying to serialize a class for exactly ?
I'm trying to store an object with a class in localStorage
It is not possible to achieve persistence this way. What you are trying to store here is an arbitrary class constructor which is code, not data. You could store a plain object representation of your code using some kind of "tag" pointing to the appropriate class, but I would not advise going this way as maintaining backward and forward compatibility can get tricky real fast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.