我在JSON文件中具有以下映射:
"mapping": [
{
"true": "some string"
},
{
"false": "some other string"
}
]
在这样的映射中,键始终是字符串。这就是为什么我需要键为字符串的原因,即使在这种情况下,它们是布尔值的字符串表示形式。
当我使用require(myfile.json)
加载此JSON文件时,密钥会以某种方式转换为实际的布尔值。
这是require()
中的错误吗?有解决方法吗?
答案 0 :(得分:1)
那不是require
的事情。 Javascript允许将任何项目用作对象键,但是在保存或检索项目时,可以在后台调用toString
。例如:
const a = {};
a[true] = 'value from true';
a[{somekey: 'somevalue'}] = 'value from object';
Object.getKeys(a); // ["true", "[object Object]"]
因此,您的问题与javascript处理对象键的方式有关。在对象密钥中存储值时,无法区分true
和'true'
:
a = {};
a[true] = 'from plain true';
a["true"] = 'from stringified true';
a[true]; // "from stringified true". See how the second assignation messes with the first, even if we are using the boolean true value as key.
以供参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects