module json.tf
The tweakstreet/json module helps with encoding and decoding data from and to JSON strings.
library json
The json library contains functions to encode and decode JSON values.
stringify
(
any x,
boolean pretty_print=true,
function date_encoder=nil,
function binary_encoder=nil
) -> string
Encodes x to a JSON string. The returned string uses the encoding conventions given in the arguments.
When pretty_print is true, whitespace is inserted to improve the readability of the resulting JSON string.
date_encoder is a function used to encode datetime values. It accepts a single datetime argument x, and
returns a value to encode in the JSON string. It must not return a datetime or binary value.
If date_encoder is nil, which is the default, datetime values are encoded using ISO date format with millisecond
precision and UTC offset.
The underlying pattern
is: uuuu-MM-dd'T'HH:mm:ss.SSSZZZZZ, and results in strings of the form: 2019-12-03T15:34:22.234+02:00.
binary_encoder is a function used to encode binary values. It accepts a single binary argument x, and
returns a value to encode in the JSON string. It must not return a datetime or binary value.
If binary_encoder is nil, which is the default, binary values are encoded as base64 strings.
Values not representable in JSON such as functions, NaN, Infinity, and -Infinity are encoded as null.
> json.stringify({:a "foo", :b "bar"})
"{
\"a\": \"foo\",
\"b\": \"bar\"
}"
> json.stringify(['hello', 1, 2019-08-16T])
"[
\"hello\",
1,
\"2019-08-16T00:00:00.000Z\"
]"
> json.stringify({:date 2014-12-24T}, date_encoder: (x) -> "date value: "..(x as string))
"{
\"date\": \"date value: 2014-12-24T00:00:00Z@UTC\"
}"
> json.stringify(123)
"123"
> json.stringify(nil)
"null"
parse
(string x, boolean lenient=true) -> any
Returns a value representing the content of given JSON string x.
Returns nil if x is nil.
If lenient is true, non-standard JSON is parsed on a best-effort basis. Examples of non-standard formats that are
likely to be successfully parsed in lenient mode include JSON with single-quoted strings and JSON with comments.
If lenient is false, only valid JSON strings are processed. An error is thrown if an invalid JSON string is
encountered.
> json.parse('{"hello": "world"}')
{
:hello "world"
}
> json.parse('[1, null, {"xs": ["x", "y", "z"]}]')
[1, nil, {
:xs ["x", "y", "z"]
}]
> json.parse(nil)
nil
# lenient
> json.parse("{'foo': 'bar'}", true)
{
:foo "bar"
}
# strict
> json.parse("{'foo': 'bar'}", false)
ERROR:
code: ILLEGAL_ARGUMENT
message: java.lang.RuntimeException: malformed JSON at line 1 column 3 path $.
...