JSON键称为“ true”,无法在JavaScript中引用JSfiddle示例

问题描述

| 首先,我使用一些在线工具将Plist(XML格式)转换为JSON,这不是问题。我设法从这个相当大的JSON文件中选择了重要的值。借助这些重要信息,我将重建一个非常精简的新JSON文件,其中包含可用于插件的信息-我将在以后创建。 从plist转换为JSON很难。在某些时候,将“ 0”和“ 1”转换为JSON,然后将其保留在JSON中:“ 2”或“ 3”。 我正在使用jQuery 检查JSfiddle以获得jsfiddle示例 或在这里
// Simplified (not really a JSON file,but this will do it for explaining) 
var themeJSON = {
    \"item\": {
        \"false\": \"\",},};

// I need to know if its enabled: \"true\" or disabled: \"false\"

// function for checking if this is the default option
function checkDefault() {
    // true is a keyword!
    if (themeJSON.item.true) {
        return \"1\";
    // so is false!
    } else(themeJSON.item.false) {
        return \"0\";
    }
}
也许我使用了诸如find()之类的其他功能? 更新了答案: 多亏了这些评论,这就是我现在所拥有的:
function checkDefault() {
    if (item.hasOwnProperty(\"true\")) {
        return \"1\";
    } else if(item.hasOwnProperty(\"false\")) {
        return \"0\";
    }
}
    

解决方法

当对象属性的名称是保留关键字时,可以使用数组索引符号来引用它。 一种检查
item
是否具有名为
false
的属性的方法:
> themeJSON.item.hasOwnProperty(\"false\");
true
这不是理想的,因为单个对象可以同时具有
false
属性和
true
属性。     ,尝试使用属性名称作为字符串:
if (themeJSON.item[\'true\']) {
  return \'1\';
}
else if (themeJSON.item[\'false\']) {
    return \"0\";
}
编辑-正确的注释指出,尽管确实可以通过字符串值访问属性,但是代码还是有缺陷的。如果确实为属性提供了空字符串值,那么您真正需要的是一种测试属性是否存在的方法,而不是(如此代码一样)仅检查属性的值:
if (typeof themeJSON.item[\'true\'] !== \'undefined\') { ... }
或者,或者:
if (\'true\' in themeJSON.item) { ... }
对空字符串进行相等性的显式检查也可以:
if (themeJSON.item[\'true\'] === \'\') { ... }
    ,在JS中,ѭ15等于
foo[\'bar\']
。拒绝:
if (themeJSON.item[\'true\'] === \"\")
注意需要将“ 18”作为“ 19”,但需要“ 20”。 另外,我必须挑剔。
themeJSON
不再是JSON,因为它不是字符串-它只是另一个JavaScript对象。您不应混淆这两个。     ,试试这个代码
function checkDefault() {
    // true is a keyword!
    if (\"true\" in themeJSON.item) {
        return \"1\";
    // so is false!
    } else if (\"false\" in themeJSON.item) {
        return \"0\";
    }
}
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...