首页 > 解决方案 > `require()` 将字符串文字“true”转换为布尔值 true

问题描述

我在 JSON 文件中有以下映射:

"mapping": [
 {
  "true": "some string"
 },
 {
  "false": "some other string"
 }
]

在这样的映射中,键总是字符串。这就是为什么我需要键是字符串,即使在这种情况下,它们是布尔值的字符串表示形式。

当我用 加载这个 JSON 文件时require(myfile.json),键会以某种方式转换为实际的布尔值。

那是一个错误require()吗?有解决方法吗?

标签: node.jsjsonrequire

解决方案


那不是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


推荐阅读