The JSON.stringify()
function is designed to convert a JavaScript value into JSON format.
console.log(JSON.stringify('a'));
//output: "a"
console.log(JSON.stringify(1));
//output: 1
console.log(JSON.stringify(true));
//output: true
However, technically speaking, the outputs above are not valid JSON formats.
"a"
1
true
The definition of JSON is provided below:
JSON is based on two main structures:
- A collection of name/value pairs. This can be represented as an object, record, struct, dictionary, hash table, keyed list, or associative array in different programming languages.
- An ordered list of values. In many languages, this is represented as an array, vector, list, or sequence.
So, if the inputs mentioned above do not produce valid JSON when passed through JSON.stringify()
, the question arises as to why that is the case?