Use these functions to encode dictionary objects into JSON strings and decode JSON strings back into dictionaries.
json_enc
| Syntax | json_enc(d) |
|---|---|
| Description | Encodes a dictionary object into a JSON string. |
| Parameters | d: The dictionary object to encode. |
| Return value | A JSON-encoded string on success, or false on failure. |
Example:
var_a = []
var_b = ['v1', 'v2']
set(var_a, 'k1', 'v1')
set(var_a, 'k2', var_b)
var_c = '{"k1":"v1","k2":["v1","v2"]}'
say(concat('json_enc=', json_enc(var_a)))
say(concat('json_dec=', get(json_dec(var_c), 'k1')))Output:
json_enc={"k1":"v1","k2":["v1","v2"]}
json_dec=v1json_dec
| Syntax | json_dec(s) |
|---|---|
| Description | Decodes a JSON string into a dictionary. |
| Parameters | s: The JSON string to decode. |
| Return value | A dictionary on success, or false on failure. |
Note
A numeric string such as "123" decodes into a variable of the number type. Before performing operations on the decoded value (such as getting a value), use the type function to check its type.
The following examples show two scenarios: decoding a numeric string and decoding a JSON object.
Example 1: Decoding a numeric string
var_c = '123'
type_var_c = type(json_dec(var_c))
if eq(type_var_c, 'table') {
say(concat('json_dec=', get(json_dec(var_c), 'k1')))
} else {
say(type_var_c)
}Output:
numberExample 2: Decoding a JSON object
var_c = '{"k1":"v1","k2":["v1","v2"]}'
type_var_c = type(json_dec(var_c))
if eq(type_var_c, 'table') {
say(concat('json_dec=', get(json_dec(var_c), 'k1')))
} else {
say(type_var_c)
}Output:
json_dec=v1