JSON密钥存在但返回false

Gar*_*t R 1 javascript json node.js

首先,我的所有代码都在node.js中完成,但这也可以应用于javascript.

这是我用来检查密钥是否存在的代码,问题是它总是返回false.所以我在console.log中添加了以显示值是什么:

if(!choice.name || !choice.realm || !choice.region || !choice.roll){
    console.log(choice);
    console.log(choice.name);
    console.log(choice.realm);
    console.log(choice.region);
    console.log(choice.roll);
    return false;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

{"name":"Imacactus","realm":"Velen","region":"US","roll":"DPS"}
undefined
undefined
undefined
undefined
Run Code Online (Sandbox Code Playgroud)

我猜这与报价有关?但是我从来没有听说过把它搞砸了.这是一个node.js问题吗?我也试过.hasOwnProperty('realm')但它仍然失败了.

这是大多数具有所有功能的代码:http://pastebin.com/DUN9VdHr

Ben*_*ick 7

您需要先将json解析为javascript对象,然后才能引用其属性.

您可以使用JSON.parse

var choiceobj = JSON.parse(choice);
if(!choiceobj.name || !choiceobj.realm || !choiceobj.region || !choiceobj.roll){

    console.log(choiceobj);
    console.log(choiceobj.name);
    console.log(choicepbj.realm);
    console.log(choiceobj.region);
    console.log(choiceobj.roll);
    return false;
Run Code Online (Sandbox Code Playgroud)

}