简体   繁体   中英

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

Here's my situation, I have a JSON that looks somewhat like this:

{
    "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") ). 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. (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? And how would I access the value this.MyType.MyValue , if I get another String MyValue ?

Thanks in advance.

Edit: I'd really like to avoid using eval, for obvious reasons. And if I have to - I guess I would need to create Dictionaries for possible JSON Values, to validate the input?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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