[英]JSON, node.js: access classes via its name (String)
這是我的情況,我有一個看起來像這樣的JSON:
{
"items": [{
"type": "condition",
"data": {
"type": "comparison",
"value1": {
"source": "MyType1",
"component": "Attribute1"
},
"value2": {
"source": "MyType2",
"component": "Attribute2"
},
"operator": "gt"
}
},
{
"type": "then",
"data": {
"result": "failed",
"message": "value1 is too high"
}
}
]
}
並希望將其翻譯為:
if (MyType1.Attribute1 > MyType2.Attribute2) {
result = "failed";
console.log("value1 is too high");
}
現在我的問題是,我不知道如何將value1
和value2
的條目轉換為實際代碼,或者更確切地說,如何訪問對象MyType1
(也許通過諸如getAttribute("MyType1")
)。 由於我將擁有大量的源頭,每個源頭都有不同的組成部分,因此我無法真正編寫龐大的詞典。 或者我想避免這種情況。
目的是允許通過一些交互式UI創建if - then - statements
,我認為最好將該代碼另存為.json
文件。 (想想規則管理系統)。
那么,TL,DR,如果只有字符串MyType可以訪問類屬性this.MyType
? 我該如何將訪問值this.MyType.MyValue
,如果我得到另一個字符串myvalue的 ?
提前致謝。
編輯:出於明顯的原因,我真的很想避免使用eval。 而且,如果我必須-我想我需要為可能的JSON值創建字典,以驗證輸入?
您需要某種解析器。 首先,我們需要某種方式來存儲變量和標志:
const variables = {};
var in = false;
然后我們遍歷代碼並執行它:
for(const command of items){
switch( command.type ){
case "condition":
//...
case "then":
//...
}
}
要訪問變量,我們可以簡單地執行
var current = variables[ identifier ];
反過來存儲它:
variables[ identifier ] = current;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.