英文:
Javascript: Reading data type from a string of the data type name, from a JSON file
问题
我有一个程序,其行为取决于属性的数据类型。在这个程序中,我可以通过类似以下方式设置数据类型:
```js
const myObject = new MyObject ();
myObject.numberType = number
myObject.main()
我想能够从一个 json 文件中读取数据类型,但我不能直接在 json 中记录数据类型,我能做的最好的就是记录一个包含与数据类型匹配的文本的字符串。
例如:
{
"type1": "number",
"type2": "string"
}
我想要将我的程序改成下面的样子,并使其表现相同:
import types from './types.json' assert { type: "json" };
// const types = require ('./types.json'); // 如果使用 es5
const myObject = new MyObject ();
myObject.numberType = types['type1']; // 这行需要做一些改变
myObject.main()
MRE
json
{
"type1": "number",
"type2": "string"
}
js
import types from './types.json' assert { type: "json" };
async function main () {
const type1 = typeof (types['type1']);
const type2 = typeof (types['type2']);
console.log (type1);
console.log (type2);
};
main ();
当前输出
string
string
期望输出
number
string
不过,我需要将实际的数据类型保存在变量中,而不是匹配数据类型的字符串。
我基本上是想在一个 json 文件中记录我的数据类型,并让我的程序以某种方式读取它。
<details>
<summary>英文:</summary>
I have a program that behaves differently depending on what the datatype of an attribute is. Within this program I can set the data type by doing something like
const myObject = new MyObject ();
myObject.numberType = number
myObject.main()
I want to be able to read the data type from a json file, but I cannot record the data types literally within the json, the best I can do is record a string containing text that matches the data type
For example
```json
{
"type1": "number",
"type2": "string"
}
I would like to change my program to look more like the program below and have it behave the same
import types from './types.json' assert { type: "json" };
// const types = require ('./types.json'); // if using es5
const myObject = new MyObject ();
myObject.numberType = types['type1']; // This line will need some changing
myObject.main()
MRE
json
{
"type1": "number",
"type2": "string"
}
js
import types from './types.json' assert { type: "json" };
async function main () {
const type1 = typeof (types['type1']);
const type2 = typeof (types['type2']);
console.log (type1);
console.log (type2);
};
main ();
current output
string
string
desired output
number
string
I need to save the actual types in the variables though, not strings whose text matches the type
I'm basically trying to record my data types within a json file and have my program read it somehow
答案1
得分: 1
const type1 = types['type1'];
const type2 = types["type2"];
英文:
const type1 = types['type1'];
const type2 = types["type2"];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论