json

JSON encoding and decoding.

var json = use('json')

Encoding

json.encode(value, space, replacer, whitelist)

Convert a value to JSON text.

json.encode({a: 1, b: 2})
// '{"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 or string)
  • 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)
log.console(loaded.debug)  // true