├── LICENSE.md ├── README.md └── _JXON.ahk /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 TheArkive 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JXON_ahk2 2 | JSON serializer for AHK v2 3 | 4 | Thanks to cocobelgica for his initial AHK v1 release [here](https://github.com/cocobelgica/AutoHotkey-JSON). 5 | 6 | The focus of this serializer is compatibility with JSON. 7 | 8 | Only Array(), Map(), or a nested combination is supported. 9 | 10 | ## jxon_dump(obj, indent:=0) 11 | 12 | ``` 13 | var := jxon_dump(obj, indent:=0) 14 | ``` 15 | 16 | Output var is the serialized text. 17 | 18 | Indent is in spaces. Leaving this param blank will output the JSON text as a single line. A value of 1 or more in this param will insert a line break at every element, and every nested level will get an additional indented space. This param indicates the number of spaces to add for indent per level. 19 | 20 | ## jxon_load(&text) 21 | 22 | ``` 23 | obj := jxon_load(&text) 24 | ``` 25 | 26 | Input must be properly formatted JSON text. If not properly formatted an error will be thrown. The error message will indicate the character number where parsing failed due to improper format. 27 | 28 | The input `&text` must be passed as a VarRef with the `&` character. This will ensure better performance and memory savings with massive input strings. -------------------------------------------------------------------------------- /_JXON.ahk: -------------------------------------------------------------------------------- 1 | ;;;; AHK v2 2 | ; Example =================================================================================== 3 | ; =========================================================================================== 4 | 5 | ; Msgbox "The idea here is to create several nested arrays, save to text with jxon_dump(), and then reload the array with jxon_load(). The resulting array should be the same.`r`n`r`nThis is what this example shows." 6 | ; a := Map(), b := Map(), c := Map(), d := Map(), e := Map(), f := Map() ; Object() is more technically correct than {} but both will work. 7 | 8 | ; d["g"] := 1, d["h"] := 2, d["i"] := ["purple","pink","pippy red"] 9 | ; e["g"] := 1, e["h"] := 2, e["i"] := Map("1","test1","2","test2","3","test3") 10 | ; f["g"] := 1, f["h"] := 2, f["i"] := [1,2,Map("a",1.0009,"b",2.0003,"c",3.0001)] 11 | 12 | ; a["test1"] := "test11", a["d"] := d 13 | ; b["test3"] := "test33", b["e"] := e 14 | ; c["test5"] := "test55", c["f"] := f 15 | 16 | ; myObj := Map() 17 | ; myObj["a"] := a, myObj["b"] := b, myObj["c"] := c, myObj["test7"] := "test77", myObj["test8"] := "test88" 18 | 19 | ; g := ["blue","green","red"], myObj["h"] := g ; add linear array for testing 20 | 21 | ; q := Chr(34) 22 | ; textData2 := Jxon_dump(myObj,4) ; ===> convert array to JSON 23 | ; msgbox "JSON output text:`r`n===========================================`r`n(Should match second output.)`r`n`r`n" textData2 24 | 25 | ; newObj := Jxon_load(&textData2) ; ===> convert json back to array 26 | 27 | ; textData3 := Jxon_dump(newObj,4) ; ===> break down array into 2D layout again, should be identical 28 | ; msgbox "Second output text:`r`n===========================================`r`n(should be identical to first output)`r`n`r`n" textData3 29 | 30 | ; msgbox "textData2 = textData3: " ((textData2=textData3) ? "true" : "false") 31 | 32 | ; =========================================================================================== 33 | ; End Example ; ============================================================================= 34 | ; =========================================================================================== 35 | 36 | ; originally posted by user coco on AutoHotkey.com 37 | ; https://github.com/cocobelgica/AutoHotkey-JSON 38 | 39 | Jxon_Load(&src, args*) { 40 | key := "", is_key := false 41 | stack := [ tree := [] ] 42 | next := '"{[01234567890-tfn' 43 | pos := 0 44 | 45 | while ( (ch := SubStr(src, ++pos, 1)) != "" ) { 46 | if InStr(" `t`n`r", ch) 47 | continue 48 | if !InStr(next, ch, true) { 49 | testArr := StrSplit(SubStr(src, 1, pos), "`n") 50 | 51 | ln := testArr.Length 52 | col := pos - InStr(src, "`n",, -(StrLen(src)-pos+1)) 53 | 54 | msg := Format("{}: line {} col {} (char {})" 55 | , (next == "") ? ["Extra data", ch := SubStr(src, pos)][1] 56 | : (next == "'") ? "Unterminated string starting at" 57 | : (next == "\") ? "Invalid \escape" 58 | : (next == ":") ? "Expecting ':' delimiter" 59 | : (next == '"') ? "Expecting object key enclosed in double quotes" 60 | : (next == '"}') ? "Expecting object key enclosed in double quotes or object closing '}'" 61 | : (next == ",}") ? "Expecting ',' delimiter or object closing '}'" 62 | : (next == ",]") ? "Expecting ',' delimiter or array closing ']'" 63 | : [ "Expecting JSON value(string, number, [true, false, null], object or array)" 64 | , ch := SubStr(src, pos, (SubStr(src, pos)~="[\]\},\s]|$")-1) ][1] 65 | , ln, col, pos) 66 | 67 | throw Error(msg, -1, ch) 68 | } 69 | 70 | obj := stack[1] 71 | is_array := (obj is Array) 72 | 73 | if i := InStr("{[", ch) { ; start new object / map? 74 | val := (i = 1) ? Map() : Array() ; ahk v2 75 | 76 | is_array ? obj.Push(val) : obj[key] := val 77 | stack.InsertAt(1,val) 78 | 79 | next := '"' ((is_key := (ch == "{")) ? "}" : "{[]0123456789-tfn") 80 | } else if InStr("}]", ch) { 81 | stack.RemoveAt(1) 82 | next := (stack[1]==tree) ? "" : (stack[1] is Array) ? ",]" : ",}" 83 | } else if InStr(",:", ch) { 84 | is_key := (!is_array && ch == ",") 85 | next := is_key ? '"' : '"{[0123456789-tfn' 86 | } else { ; string | number | true | false | null 87 | if (ch == '"') { ; string 88 | i := pos 89 | while i := InStr(src, '"',, i+1) { 90 | val := StrReplace(SubStr(src, pos+1, i-pos-1), "\\", "\u005C") 91 | if (SubStr(val, -1) != "\") 92 | break 93 | } 94 | if !i ? (pos--, next := "'") : 0 95 | continue 96 | 97 | pos := i ; update pos 98 | 99 | val := StrReplace(val, "\/", "/") 100 | val := StrReplace(val, '\"', '"') 101 | , val := StrReplace(val, "\b", "`b") 102 | , val := StrReplace(val, "\f", "`f") 103 | , val := StrReplace(val, "\n", "`n") 104 | , val := StrReplace(val, "\r", "`r") 105 | , val := StrReplace(val, "\t", "`t") 106 | 107 | i := 0 108 | while i := InStr(val, "\",, i+1) { 109 | if (SubStr(val, i+1, 1) != "u") ? (pos -= StrLen(SubStr(val, i)), next := "\") : 0 110 | continue 2 111 | 112 | xxxx := Abs("0x" . SubStr(val, i+2, 4)) ; \uXXXX - JSON unicode escape sequence 113 | if (xxxx < 0x100) 114 | val := SubStr(val, 1, i-1) . Chr(xxxx) . SubStr(val, i+6) 115 | } 116 | 117 | if is_key { 118 | key := val, next := ":" 119 | continue 120 | } 121 | } else { ; number | true | false | null 122 | val := SubStr(src, pos, i := RegExMatch(src, "[\]\},\s]|$",, pos)-pos) 123 | 124 | if IsInteger(val) 125 | val += 0 126 | else if IsFloat(val) 127 | val += 0 128 | else if (val == "true" || val == "false") 129 | val := (val == "true") 130 | else if (val == "null") 131 | val := "" 132 | else if is_key { 133 | pos--, next := "#" 134 | continue 135 | } 136 | 137 | pos += i-1 138 | } 139 | 140 | is_array ? obj.Push(val) : obj[key] := val 141 | next := obj == tree ? "" : is_array ? ",]" : ",}" 142 | } 143 | } 144 | 145 | return tree[1] 146 | } 147 | 148 | Jxon_Dump(obj, indent:="", lvl:=1) { 149 | if IsObject(obj) { 150 | If !(obj is Array || obj is Map || obj is String || obj is Number) 151 | throw Error("Object type not supported.", -1, Format("", ObjPtr(obj))) 152 | 153 | if IsInteger(indent) 154 | { 155 | if (indent < 0) 156 | throw Error("Indent parameter must be a postive integer.", -1, indent) 157 | spaces := indent, indent := "" 158 | 159 | Loop spaces ; ===> changed 160 | indent .= " " 161 | } 162 | indt := "" 163 | 164 | Loop indent ? lvl : 0 165 | indt .= indent 166 | 167 | is_array := (obj is Array) 168 | 169 | lvl += 1, out := "" ; Make #Warn happy 170 | for k, v in obj { 171 | if IsObject(k) || (k == "") 172 | throw Error("Invalid object key.", -1, k ? Format("", ObjPtr(obj)) : "") 173 | 174 | if !is_array ;// key ; ObjGetCapacity([k], 1) 175 | out .= (ObjGetCapacity([k]) ? Jxon_Dump(k) : escape_str(k)) (indent ? ": " : ":") ; token + padding 176 | 177 | out .= Jxon_Dump(v, indent, lvl) ; value 178 | . ( indent ? ",`n" . indt : "," ) ; token + indent 179 | } 180 | 181 | if (out != "") { 182 | out := Trim(out, ",`n" . indent) 183 | if (indent != "") 184 | out := "`n" . indt . out . "`n" . SubStr(indt, StrLen(indent)+1) 185 | } 186 | 187 | return is_array ? "[" . out . "]" : "{" . out . "}" 188 | 189 | } Else If (obj is Number) 190 | return obj 191 | 192 | Else ; String 193 | return escape_str(obj) 194 | 195 | escape_str(obj) { 196 | obj := StrReplace(obj,"\","\\") 197 | obj := StrReplace(obj,"`t","\t") 198 | obj := StrReplace(obj,"`r","\r") 199 | obj := StrReplace(obj,"`n","\n") 200 | obj := StrReplace(obj,"`b","\b") 201 | obj := StrReplace(obj,"`f","\f") 202 | obj := StrReplace(obj,"/","\/") 203 | obj := StrReplace(obj,'"','\"') 204 | 205 | return '"' obj '"' 206 | } 207 | } 208 | 209 | --------------------------------------------------------------------------------