JSON.PARSE与零元素(node.js)的数组一起使用



根据文档json.parse将第一个参数作为字符串作为字符串。我发现了一种意外的行为:

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

我希望它会失败,因为提供的输入参数是一个数组。相比之下,JSON.parse成功解析了数组[0]元素一个将其打印出来(在node.js中)。

但是,如果您传递了带有两个元素的数组,则JSON.parse会出错

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

为什么这样?

json.parse是一种期望字符串的内部JS方法。但是,如果给出了其他类型,它将将其转换为字符串。对于一个数组,转换为字符串为 array.join(',')

因此,当具有一个元素时,它将仅将第一个元素转换为字符串。当提供json.parse多个元素的数组时,它将出错,因为输入json将不有效。

最新更新