JSON is a text representation of some data structure (usually an array or an object) but primitive values like strings, numbers and boolean values can also be encoded as JSON (and successfully decoded).
Assuming both strings you want to decode were valid JSON, the code that produces them should look like:
var x = 123;
var a = JSON.stringify(x);
// a == '123'
var y = W-11;
var b = JSON.stringify(y);
// b != 'W-11'
If you try to run this code, the statement y = W-11
triggers a ReferenceError ("W is not defined").
Or, if the W
variable is defined, W-11
is a subtraction that tries to convert W
to a number and the result is a number (or NaN
).
Either way, it is impossible to generate W-11
using JSON.stringify()
(because it is not valid JSON). What you probably want is to parse the string "W-11"
and get W-11
as the value encoded to produce it:
console.log(JSON.parse('"W-11"'));
// W-11
Your confusion comes from the fact that in the JavaScript code the strings are surrounded by quotes or apostrophes. This is how the interpreter knows that the characters between the quotes represent themselves and they must not be interpreted as code.
In code, 'W-11'
is a string encoded as JavaScript while the actual value of the string is W-11
(no quotes). You can also write it in JavaScript code as as "W-11"
or `W-11`
.