Get a value from a JSON StringTag(s): WinApi/Registry


Parsing a JSON string to retrieve a value is not something easy in Powerscript. One way to achieve that is to embed a JScript code in Powerscript using the COM object MSScriptControl.ScriptControl and let the JScript engine do the work. A real JSON parser is not available with the script engine is used this way, but the eval() function can be used for simple JSON string (see the important note below).
OleObject lole_ScriptControl
String ls_json
String ls_value

lole_ScriptControl = CREATE OleObject
lole_ScriptControl.ConnectToNewObject( "MSScriptControl.ScriptControl" )
lole_ScriptControl.Language = "JScript"
lole_ScriptControl.AddCode("function getValue(s,key) {eval(~"jsonobj=~" + s); return eval(~"jsonobj.~" + key) ; }")

//           key      value
ls_json = "{ test1 : 'value1' , test2 : 'value2' }"
TRY
   ls_value =  lole_ScriptControl.Eval ("getValue(~"" +ls_json + "~", ~"test1~");")
   MessageBox("", ls_value)
   ls_value =  lole_ScriptControl.Eval ("getValue(~"" +ls_json + "~", ~"test2~");")
   MessageBox("", ls_value)
CATCH ( Throwable e )
   MessageBox("Err", e.GetMessage())
END TRY
Since the JSON string has single quote to represent strings, I use double quotes to pass the JSON string to the JScript function.

IMPORTANT NOTE

You have to make sure that the JSON string is valid and from a trusted source because this technique (using eval() and not a real JSON parser) is not safe and can be used to inject and execute malicious code.

See also this HowTo : Get a value from a REST service


blog comments powered by Disqus