forked from Ixiko/AHK-libs-and-classes-collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSON_FromObj.ahk
47 lines (42 loc) · 1.58 KB
/
JSON_FromObj.ahk
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
; Copyright © 2013 VxE. All rights reserved.
; Serialize an object as JSON-like text OR format a string for inclusion therein.
; NOTE: scientific notation is treated as a string and hexadecimal as a number.
; NOTE: UTF-8 sequences are encoded as-is, NOT as their intended codepoint.
json_fromobj( obj ) {
If IsObject( obj )
{
isarray := 0 ; an empty object could be an array... but it ain't, says I
for key in obj
if ( key != ++isarray )
{
isarray := 0
Break
}
for key, val in obj
str .= ( A_Index = 1 ? "" : "," ) ( isarray ? "" : json_fromObj( key ) ":" ) json_fromObj( val )
return isarray ? "[" str "]" : "{" str "}"
}
else if obj IS NUMBER
return obj
; else if obj IN null,true,false ; AutoHotkey does not natively distinguish these
; return obj
; Encode control characters, starting with backslash.
StringReplace, obj, obj, \, \\, A
StringReplace, obj, obj, % Chr(08), \b, A
StringReplace, obj, obj, % A_Tab, \t, A
StringReplace, obj, obj, `n, \n, A
StringReplace, obj, obj, % Chr(12), \f, A
StringReplace, obj, obj, `r, \r, A
StringReplace, obj, obj, ", \", A
StringReplace, obj, obj, /, \/, A
While RegexMatch( obj, "[^\x20-\x7e]", key )
{
str := Asc( key )
val := "\u" . Chr( ( ( str >> 12 ) & 15 ) + ( ( ( str >> 12 ) & 15 ) < 10 ? 48 : 55 ) )
. Chr( ( ( str >> 8 ) & 15 ) + ( ( ( str >> 8 ) & 15 ) < 10 ? 48 : 55 ) )
. Chr( ( ( str >> 4 ) & 15 ) + ( ( ( str >> 4 ) & 15 ) < 10 ? 48 : 55 ) )
. Chr( ( str & 15 ) + ( ( str & 15 ) < 10 ? 48 : 55 ) )
StringReplace, obj, obj, % key, % val, A
}
return """" obj """"
} ; json_fromobj( obj )