class JSON static JS JSON _GetJScripObject decode JsonString try oJSON

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
class JSON
{
static JS := JSON._GetJScripObject()
decode(JsonString)
{
try
oJSON := this.JS.("(" JsonString ")")
catch
Return "Wrong JsonString!"
Return this._CreateObject(oJSON)
}
GetFromUrl(url, contentType := "", userAgent := "", body := "")
{
; в случае удачи будет возвращена JSON-строка, в случае ошибки — массив с одним элементом-строкой с описанием ошибки
try
{
XmlHttp := ComObjCreate("Microsoft.XmlHttp")
XmlHttp.Open("GET", url, false)
( contentType && XmlHttp.SetRequestHeader("Content-Type", contentType) )
( userAgent && XmlHttp.SetRequestHeader("User-Agent", userAgent) )
XmlHttp.Send(body)
}
catch e
Return ["Error!`n" . e.Message]
status := XmlHttp.Status
Return status = 200 ? XmlHttp.ResponseText : ["Error! Status: " . status . ", ResponseText: " . XmlHttp.ResponseText]
}
encode(obj)
{
Return this.JS.("JSON.stringify(" . this._ObjToString(obj) . ")")
}
_ObjToString(obj)
{
if IsObject(obj)
{
isArray := true
for key in obj
{
if IsObject(key)
Return "Invalid key"
if !(key = A_Index || isArray := false)
break
}
for k, v in obj
str .= (A_Index = 1 ? "" : ",") . (isArray ? "" : k . ":") . this._ObjToString(v)
Return isArray ? "[" str "]" : "{" str "}"
}
else if !(obj*1 = "" || RegExMatch(obj, "\s"))
Return obj
else
Return """" obj """"
}
_GetJScripObject()
{
static doc
doc := ComObjCreate("htmlfile")
doc.write("<meta http-equiv=""X-UA-Compatible"" content=""IE=9"">")
JS := ObjBindMethod(doc.parentWindow, "eval")
JSON._AddMethods(JS)
Return JS
}
_AddMethods(ByRef JS)
{
JScript =
(
Object.prototype.GetKeys = function ()
{
var keys = []
for (var k in this)
if (this.hasOwnProperty(k))
keys.push(k)
return keys
}
Object.prototype.IsArray = function ()
{
var toStandardString = {}.toString
return toStandardString.call(this) == '[object Array]'
}
)
JS.("delete ActiveXObject; delete GetObject;")
JS.(JScript)
}
_CreateObject(ObjJS)
{
res := ObjJS.IsArray()
if (res = "")
Return ObjJS
else if (res = -1)
{
obj := []
Loop % ObjJS.length
obj[A_Index] := this._CreateObject(ObjJS[A_Index - 1])
}
else if (res = 0)
{
obj := {}
keys := ObjJS.GetKeys()
Loop % keys.length
k := keys[A_Index - 1], obj[k] := this._CreateObject(ObjJS[k])
}
Return obj
}
}