3

The JSON.stringify() method converts a JavaScript value to a JSON

console.log(JSON.stringify('a'));
//produce "a"
console.log(JSON.stringify(1));
//produce 1
console.log(JSON.stringify(true));
//produce true

but according to the definition these are not JSON

"a"
1
true

JSON definition is showing below

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

my question is JSON.stringify() not producing JSON when input above values why is that ?

Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
Sachithrra Dias
  • 185
  • 1
  • 2
  • 11

1 Answers1

4

The JSON.stringify() method converts a JavaScript 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.

Ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

"my question is JSON.stringify() not producing JSON when input above values why is that?"

These are all Valid JSON syntax representing JSON value:

"a"
1
true
{}
[]

Check this:

JSON.parse('"foo"'); // returns "foo"
JSON.parse(1); // returns 1
JSON.parse(true); // returns true
JSON.parse('{}'); // returns {}
JSON.parse('[]');  // returns []

For more clarification this check these answers:

Is this simple string considered valid JSON?

What is the minimum valid JSON?

Community
  • 1
  • 1
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58