Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
47 lines (42 sloc) 1.58 KB
; 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 )