class Json extends Object
Converts between JSON text and script values. Both methods are called on the class itself; a Json object is never constructed.
The class is exported by the KS module:
#Import "Ks" { Json }
Returns the JSON text for a script value.
JsonText := Json.Encode(Value)
Type: Any
The value to encode. See Type Mapping for how each type is represented.
Type: String
Returns the JSON text, without insignificant whitespace.
A ValueError is thrown if Value contains itself, directly or through another container, or if it nests more than 128 levels deep.
Returns the script value for JSON text.
Value := Json.Decode(JsonText)
Type: String
The JSON text to decode. Any JSON value is accepted, not only an object or array. Trailing commas and comments are tolerated.
Type: Any
Returns the decoded value. See Type Mapping.
A ValueError is thrown if JsonText is not well-formed JSON. Its message describes the position of the problem.
| JSON | Script value | Direction |
|---|---|---|
| object | Map | Both. Encoding also accepts an Object, whose own value properties become members. |
| array | Array | Both |
| string | String | Both |
| number | Integer or Float | Both. Decoding produces an Integer when the value is integral and fits in 64 bits, otherwise a Float. |
| true / false | 1 / 0 | Decoding only. A script has no separate boolean type, so true becomes 1 and false becomes 0, and re-encoding those writes numbers. |
| null | empty string | Decoding only. Encoding writes null only for a value which is unset. |
Only an object's own value properties are encoded. A dynamic property would have to be called to produce a value, which encoding does not do, so such properties and methods are skipped.
Note: Because true, false and null decode to ordinary script values, a decode followed by an encode does not always reproduce the original text, even though the result is equivalent JSON.
Reads a value out of JSON text.
#Import "Ks" { Json }
Data := Json.Decode('{"name": "Keysharp", "tags": ["automation", "dotnet"], "stars": 42}')
MsgBox Data["name"] ; Keysharp
MsgBox Data["tags"][1] ; automation
MsgBox Data["stars"] + 1 ; 43, because it decoded as an Integer
#Import "Ks" { Json }
Settings := Map("theme", "dark", "size", 14, "recent", ["a.ks", "b.ks"])
MsgBox Json.Encode(Settings) ; {"theme":"dark","size":14,"recent":["a.ks","b.ks"]}
#Import "Ks" { Json }
Path := A_ScriptDir "\settings.json"
Settings := FileExist(Path) ? Json.Decode(FileRead(Path)) : Map()
Settings["runs"] := (Settings.Has("runs") ? Settings["runs"] : 0) + 1
if FileExist(Path)
FileDelete Path
FileAppend Json.Encode(Settings), Path