Generate Variables From JSON

From RPTools Wiki
Revision as of 17:04, 14 March 2023 by Taustin (talk | contribs) (Text replacement - "source>" to "syntaxhighlight>")
Jump to navigation Jump to search

When working with string properties, the varsFromStrProp() function is an automated way to generate variables from the keys within a string property. For example, if you have the following string property:

<source lang="mtmacro" line> [prop = "name=Axe; damage=1d12; proficiency=2;"] </syntaxhighlight>

You can use varsFromStrProp() to generate a variable for each key - in other words, using the function to generate a list of locally accessible variables name, damage, and proficiency.

There is no equivalent function for JSON objects. However, the following routine can be inserted into any macro to efficiently generate the variables in question.


<source lang="mtmacro"> [h:varList=json.fields(testObj)]

[h,foreach(var,varList),CODE: {

    [value = json.get(testObj,var)]
    [set(var,value)]

}] </syntaxhighlight>


The variable testObj represents the JSON object that is fed into the routine. The variables generated will be available within the scope of the running macro (but not outside).