简体   繁体   English

JSON,node.js:通过其名称(字符串)访问类

[英]JSON, node.js: access classes via its name (String)

Here's my situation, I have a JSON that looks somewhat like this: 这是我的情况,我有一个看起来像这样的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"
            }
        }
    ]
}

and would want it to translate to: 并希望将其翻译为:

if (MyType1.Attribute1 > MyType2.Attribute2) {
    result = "failed";
    console.log("value1 is too high");
}

Now my problem is, I don't know how I would translate the entries of value1 and value2 to actual code, or rather, how I could access the Object MyType1 (maybe through something like getAttribute("MyType1") ). 现在我的问题是,我不知道如何将value1value2的条目转换为实际代码,或者更确切地说,如何访问对象MyType1 (也许通过诸如getAttribute("MyType1") )。 Since I am going to have a whole bunch of sources which each have different components, I cant really write a huge dictionary. 由于我将拥有大量的源头,每个源头都有不同的组成部分,因此我无法真正编写庞大的词典。 Or I would like to avoid it. 或者我想避免这种情况。

The goal is to allow creating if - then - statements via some interactive UI, and I figured it'd be best to save that code as .json files. 目的是允许通过一些交互式UI创建if - then - statements ,我认为最好将该代码另存为.json文件。 (Think rule management system). (想想规则管理系统)。

So, TL,DR, How would I access a Class Attribute this.MyType , if I only have a String MyType to go from? 那么,TL,DR,如果只有字符串MyType可以访问类属性this.MyType And how would I access the value this.MyType.MyValue , if I get another String MyValue ? 我该如何将访问值this.MyType.MyValue ,如果我得到另一个字符串myvalue的

Thanks in advance. 提前致谢。

Edit: I'd really like to avoid using eval, for obvious reasons. 编辑:出于明显的原因,我真的很想避免使用eval。 And if I have to - I guess I would need to create Dictionaries for possible JSON Values, to validate the input? 而且,如果我必须-我想我需要为可能的JSON值创建字典,以验证输入?

You need some kind of parser. 您需要某种解析器。 At first we need some way to store variables and maybe flags: 首先,我们需要某种方式来存储变量和标志:

const variables = {};
var in = false;

Then we go through the code and execute it: 然后我们遍历代码并执行它:

for(const command of items){
  switch( command.type ){
   case "condition":
     //...
   case "then":
    //...
  }
}

To access a variable we can simply do 要访问变量,我们可以简单地执行

var current = variables[ identifier ];

To store its the other way round: 反过来存储它:

variables[ identifier ] = current;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM