;~ http://www.autohotkey.com/board/topic/93300-what-format-to-store-settings-in/#entry588268
json = {"version":"1","window":{"state":3,"screenX":25,"screenY":25,"width":790,"height":605,"test":{"nested":"object"}},"sidebar":{"visible":false,"width":"200"}}
j := parseJson(json)
MsgBox % j.version
MsgBox % j.window.screenY
return
parseJson(jsonStr){
SC := ComObjCreate("ScriptControl")
SC.Language := "JScript"
ComObjError(false)
jsCode =
(
function arrangeForAhkTraversing(obj){
if(obj instanceof Array){
for(var i=0 ; i<obj.length ; ++i)
obj[i] = arrangeForAhkTraversing(obj[i]) ;
return ['array',obj] ;
}else if(obj instanceof Object){
var keys = [], values = [] ;
for(var key in obj){
keys.push(key) ;
values.push(arrangeForAhkTraversing(obj[key])) ;
}
return ['object',[keys,values]] ;
}else
return [typeof obj,obj] ;
}
)
SC.ExecuteStatement(jsCode "; obj=" jsonStr)
return convertJScriptObjToAhks( SC.Eval("arrangeForAhkTraversing(obj)") )
}
convertJScriptObjToAhks(jsObj){
if(jsObj[0]="object"){
obj := {}, keys := jsObj[1][0], values := jsObj[1][1]
loop % keys.length
obj[keys[A_INDEX-1]] := convertJScriptObjToAhks( values[A_INDEX-1] )
return obj
}else if(jsObj[0]="array"){
array := []
loop % jsObj[1].length
array.insert(convertJScriptObjToAhks( jsObj[1][A_INDEX-1] ))
return array
}else
return jsObj[1]
}
string={hello:'world',its:{over:9000},foo:['bar']}
msgbox,% jsonGet(string,"hello")
msgbox,% jsonGet(string,"its.over")
msgbox,% jsonGet(string,"foo[0]")
obj:={hello:"world",its:{over:9000},foo:["bar"]}
msgbox,% jsonBuild(obj)
string={hello:'world',its:{over:9000},foo:['bar']}
obj:=jsonAHK(string)
msgbox,% obj.hello
msgbox,% obj.its.over
msgbox,% obj.foo.0
jsonAHK(s){
static o:=comobjcreate("scriptcontrol")
o.language:="jscript"
return o.eval("(" s ")")
}
jsonBuild(j) {
for x,y in j
s.=((a:=(j.setcapacity(0)=(j.maxindex()-j.minindex()+1)))?"":x ":")(isobject(y)?jsonBuild(y):y/y||y==0?y:"'" y "'") ","
;s.=x ":" (isobject(y)?jsonBuild(y):y/y||y==0?y:"'" y "'") ","
return (a?"[" rtrim(s,",") "]":"{" rtrim(s,",") "}")
;return ("{" rtrim(s,",") "}")
}
jsonGet(s,k){
static o:=comobjcreate("scriptcontrol")
o.language:="jscript"
return o.eval("(" s ")." k)
}