node.js - `require()` 将字符串文字“true”转换为布尔值 true
问题描述
我在 JSON 文件中有以下映射:
"mapping": [
{
"true": "some string"
},
{
"false": "some other string"
}
]
在这样的映射中,键总是字符串。这就是为什么我需要键是字符串,即使在这种情况下,它们是布尔值的字符串表示形式。
当我用 加载这个 JSON 文件时require(myfile.json)
,键会以某种方式转换为实际的布尔值。
那是一个错误require()
吗?有解决方法吗?
解决方案
那不是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
推荐阅读
- r - 如何使用summary()避免具有字符和整数的ar表中的“长度”、“类”、“模式”?
- python - 在网络驱动器上创建指向同一网络驱动器上文件的符号链接 (Win10)
- docker - 对 Dockerfile 中复制的文件设置不同的用户权限
- python - 在 macOS Catalina 上安装 pip 时出现错误“ImportError:无法导入名称 md5”
- node.js - 在 .next/ 文件夹下提供静态文件,但 url 位置不同
- performance - 更新 MongoDB 中的批量数据
- azure-active-directory - 令牌中的无效受众声明用作令牌的 JSON Web 令牌 (JWT) 没有正确的受众。确保您使用的是正确的令牌
- sql - 结合 2 个表,每个表都有不同的数据
- python - Python 和 Snowflake 回滚不会在循环迭代内的特定条件下执行
- javascript - 如何防止科尔多瓦应用程序从后退按钮关闭 - Android