beetlebug▾
/

ztcl::json parse

Gives the Tcl value of a JSON text.

ztcl::json parse ?-null VALUE? ?-typed? ?--? TEXT

Description

Reads TEXT, one JSON value with optional white space around it, and gives its Tcl value:

A lone surrogate in a \u escape becomes U+FFFD. An empty TEXT and a text with more than one value are syntax errors.

Arguments

ArgumentTypeDefaultDescription
TEXTJSON textrequiredThe text to read.

Options

OptionTypeDefaultDescription
-nullstringnoneGives the value of a JSON null.
-typedflagnoneGives a tree that keeps each JSON type.
--flagnoneEnds the options.

-null VALUE

Gives the value of a JSON null.

Each null of TEXT becomes VALUE. With no -null, a null is an error.

% ztcl::json parse -null NULL {[null, 1]}
NULL 1
% ztcl::json parse null
json syntax error at line 1, column 1: null needs the option -null
-errorcode ZT JSON NULL

-typed

Gives a tree that keeps each JSON type.

Gives a tagged tree: {object {KEY TREE ...}}, {array {TREE ...}}, {string S}, {number TEXT}, {bool true} or {bool false}, and null. A number keeps its text. encode -typed writes the tree back.

% ztcl::json parse -typed {{"a": [1, "x", true, null]}}
object {a {array {{number 1} {string x} {bool true} null}}}
% ztcl::json parse -bogus x
bad option "-bogus": must be -null, -typed, or --
-errorcode ZT JSON OPTION

--

Ends the options.

The next argument is TEXT, also when it starts with -.

% ztcl::json parse -- {"x"}
x

A flag has no value to check.

Returns

The Tcl value, or the typed tree with -typed.

Examples

Each example of this page runs after package require ztcl::json.

% ztcl::json parse {{"a": [1, 2]}}
a {1 2}

% ztcl::json parse {{"a": 1, "a": 2, "b": 3}}
a 2 b 3

% ztcl::json parse {[1, 2.0, 1e2, 99999999999999999999]}
1 2.0 100.0 99999999999999999999

% ztcl::json parse {[true, false]}
true false

Errors

% ztcl::json parse {[1,}
json syntax error at line 1, column 4: value expected
-errorcode ZT JSON SYNTAX 1 4

% ztcl::json parse {}
json syntax error at line 1, column 1: no value
-errorcode ZT JSON SYNTAX 1 1

% ztcl::json parse
wrong # args: should be "ztcl::json parse ?-null value? ?-typed? ?--? text"
-errorcode TCL WRONGARGS

Facts

Capability
None.
Tcl release
Tcl 9.1 and 8.6.
Since
ztcl 1.0.0-beta.1

See also