1.8 KiB
1.8 KiB
title, description, weight, type
| title | description | weight | type |
|---|---|---|---|
| json | JSON encoding and decoding | 80 | docs |
JSON encoding and decoding.
var json = use('json')
Encoding
json.encode(value, space, replacer, whitelist)
Convert a value to JSON text. With no space argument, output is pretty-printed with 1-space indent. Pass false or 0 for compact single-line output.
json.encode({a: 1, b: 2})
// '{ "a": 1, "b": 2 }'
// Compact (no whitespace)
json.encode({a: 1, b: 2}, false)
// '{"a":1,"b":2}'
// Pretty print with 2-space indent
json.encode({a: 1, b: 2}, 2)
// '{
// "a": 1,
// "b": 2
// }'
Parameters:
- value — the value to encode
- space — indentation: number of spaces, string, or
false/0for compact output. Default is pretty-printed. - replacer — function to transform values
- whitelist — array of keys to include
// With replacer
json.encode({a: 1, b: 2}, null, function(key, value) {
if (key == "b") return value * 10
return value
})
// '{"a":1,"b":20}'
// With whitelist
json.encode({a: 1, b: 2, c: 3}, null, null, ["a", "c"])
// '{"a":1,"c":3}'
Decoding
json.decode(text, reviver)
Parse JSON text to a value.
json.decode('{"a":1,"b":2}')
// {a: 1, b: 2}
json.decode('[1, 2, 3]')
// [1, 2, 3]
Parameters:
- text — JSON string to parse
- reviver — function to transform parsed values
// With reviver
json.decode('{"date":"2024-01-15"}', function(key, value) {
if (key == "date") return parse_date(value)
return value
})
Example
var json = use('json')
// Save configuration
var config = {
debug: true,
maxRetries: 3,
endpoints: ["api.example.com"]
}
var config_text = json.encode(config, 2)
// Load configuration
var loaded = json.decode(config_text)
print(loaded.debug) // true