Andrew Marin
Andrew Marin

Reputation: 1083

JSON.parse works with array with zero elements (node.js)

According to the documentation JSON.parse takes first argument as a string. I found an unexpected behaviour:

try {
    const a = JSON.parse([
        '{"helloworld": 1}',
    ]);
    console.log(a);
} catch (ex) {
    console.error(ex);
}

I expected it to fail as the provided input argument is an array. In contrast, JSON.parse successfully parses array[0] element an prints it out (in node.js).

However, if you pass array with two elements, JSON.parse will error out

try {
    const b = JSON.parse([
        '{"hello": 1}',
        '{"hello2": 2}',
    ]);
    console.log(b);
} catch (ex) {
    console.error(ex);
}

Why is that so?

Upvotes: 1

Views: 149

Answers (1)

Andrew Marin
Andrew Marin

Reputation: 1083

JSON.parse is an internal JS method that expects a string. However, if the other type is given, it will convert it to string. For an array the conversion to string is array.join(',').

Therefore, when having one element, it will just convert first element to string. When providing an array with more than one element to JSON.parse, it will error out as the input JSON won't be valid.

Upvotes: 1

Related Questions