Json

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 }

Table of Contents

Encode

Returns the JSON text for a script value.

JsonText := Json.Encode(Value)

Parameters

Value

Type: Any

The value to encode. See Type Mapping for how each type is represented.

Return Value

Type: String

Returns the JSON text, without insignificant whitespace.

Errors

A ValueError is thrown if Value contains itself, directly or through another container, or if it nests more than 128 levels deep.

Decode

Returns the script value for JSON text.

Value := Json.Decode(JsonText)

Parameters

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.

Return Value

Type: Any

Returns the decoded value. See Type Mapping.

Errors

A ValueError is thrown if JsonText is not well-formed JSON. Its message describes the position of the problem.

Type Mapping

JSONScript valueDirection
objectMapBoth. Encoding also accepts an Object, whose own value properties become members.
arrayArrayBoth
stringStringBoth
numberInteger or FloatBoth. Decoding produces an Integer when the value is integral and fits in 64 bits, otherwise a Float.
true / false1 / 0Decoding only. A script has no separate boolean type, so true becomes 1 and false becomes 0, and re-encoding those writes numbers.
nullempty stringDecoding 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.

Examples

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

Builds JSON text from a Map.

#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"]}

Round-trips a settings file.

#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

Map, Array, FileRead, KS module