1

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 ?

Stefan Bürscher
  • 123
  • 1
  • 1
  • 12

2 Answers2

13

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
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    what problem with var foo = new Date(); json = JSON.stringify(foo); ? – Nalin Aggarwal Aug 26 '16 at 20:23
  • 2
    because `foo` is a Date object, which is code+data. JSON can NOT represent code. While maybe that's ab ad example, because Date objects can be serialized down to a string date by JSON.stringify(), it's just an example. When you json decode that date, you don't get a Date object back, you just have a string. – Marc B Aug 26 '16 at 20:24
  • 1
    ohaky !! thanx :) – Nalin Aggarwal Aug 26 '16 at 20:27
-4

To convert JS data object to JSON , you can use JSON.stringify()

Exmaple

Input :-

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
JSON.stringify(person)

Output:

"{"firstName":"John","lastName":"Doe","age":50,"eyeColor":"blue"}"
Nalin Aggarwal
  • 886
  • 5
  • 8