Sagar
Sagar

Reputation: 19

Json.parse considers number as a string as valid json object

const isJson = ( str ) => {
    try {
        var res = JSON.parse( str );

    } catch ( e ) {
        return false;
    }
    return true;
};

console.log(isJson('W-11'));

This code returns false.

const isJson = ( str ) => {
    try {
        var res = JSON.parse( str );

    } catch ( e ) {
        return false;
    }
    return true;
};

console.log(isJson('123'));

This returns true.

Need to know why json.parse treats pure number as string a valid json and string with character not valid json. Apologies if it is a newbie question.

Upvotes: 0

Views: 2754

Answers (3)

axiac
axiac

Reputation: 72216

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`.

Upvotes: 1

Atishay Jain
Atishay Jain

Reputation: 1445

If you want 'W-11' to work pass it like this '"W-1"' in isJSON function

If it's doublequoted then it's a string else it's a numeric, boolean, null.

Upvotes: 0

deceze
deceze

Reputation: 522042

111

Is a valid JSON literal value. JSON supports number literals, and this is one.

W-11

This is invalid JSON. The characters W and - have no meaning in the JSON spec (well, - would be part of negative number literals, but anyway…). If you want to form a JSON string literal, this would be one:

"W-11"

So:

JSON.parse('"W-11"')  // ok

The contents of your Javascript string must be valid JSON. W-11 isn't a string to JSON, only "W-11" is.

Upvotes: 0

Related Questions