Files
cell/docs/library/json.md

96 lines
1.6 KiB
Markdown

---
title: "json"
description: "JSON encoding and decoding"
weight: 80
type: "docs"
---
JSON encoding and decoding.
```javascript
var json = use('json')
```
## Encoding
### json.encode(value, space, replacer, whitelist)
Convert a value to JSON text.
```javascript
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
```javascript
// 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.
```javascript
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
```javascript
// With reviver
json.decode('{"date":"2024-01-15"}', function(key, value) {
if (key == "date") return parse_date(value)
return value
})
```
## Example
```javascript
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
```