Stefan Bürscher Stefan Bürscher - 5 months ago 18
Javascript Question

How to convert JS Object to JSON

Is it posible to convert a js object to json or is a js object exactly a JSON ? Can someone tell me what a JSON exactly is ?


Quite literally, JSON is a stricter format for what is basically the right-hand side of a Javascript variable assignment. It's a text-based encoding of Javascript data:

var foo = ...json goes here ...;

JSON can be ANY valid Javascript data-only structure. A boolean, an int, a string, even arrays and objects. What JSON ISN'T is a general serialization format. Something like this

var foo = new Date();
json = JSON.stringify(foo); // json gets the string "2016-08-26 etc..."
newfoo = JSON.parse(json);  // newfoo is now a string, NOT a "Date" object.

will not work. The Date object will get serialized to a JSON string, but deserializing the string does NOT give you a Date object again. It'll just be a string.

JSON can only represent DATA, not CODE. That includes expressions

var foo = 2; // "2" is valid json
var foo = 1+1; // invalid - json does not have expressions.
var foo = {"bar":["baz"]}; // also valid JSON
var foo = [1,2,3+4]; // fails - 3+4 is an expression