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:
- an object is a dict; a key that comes again keeps its first place and gets the last value, as
dict createdoes; - an array is a list, and a string is a string;
- a number that is an integer is an integer, also above 64 bits, and each other number is a double:
1e2gives100.0; trueandfalsegive the stringstrueandfalse;nullis an error with the codeZT JSON NULL, unless-nullgives its 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
| Argument | Type | Default | Description |
|---|---|---|---|
| TEXT | JSON text | required | The text to read. |
Options
| Option | Type | Default | Description |
|---|---|---|---|
-null | string | none | Gives the value of a JSON null. |
-typed | flag | none | Gives a tree that keeps each JSON type. |
-- | flag | none | Ends 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"}
xA 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