# Module /codec/json

Fast bidirectional JSON serialization (encode, decode, from-json) and derivable To-JSON / From-JSON support.

```tangu
(use /codec/json)
```

## Traits

### From-JSON

`Trait` in `/codec/json`

Trait allowing structs and types to be hydrated from decoded JSON data via `(derive My-Struct From-JSON)` or custom `(impl From-JSON My-Struct ...)`.

- `` — 

### To-JSON

`Trait` in `/codec/json`

Trait allowing types and structs to override default field-by-field JSON serialization.

- `` — 

## Functions & symbols

### decode

`(json/decode json-string) -> Any`

Parses a JSON text string or Slab byte buffer into native Tangu Maps, Lists, Numbers, Strings, Booleans, or `()`. When a `Target-Type` is provided as the second argument, hydrates the decoded data into the specified Struct or compound type via `From-JSON`. Returns an Error if malformed.

| Parameter | Type | Optional | Description |
| :--- | :--- | :--- | :--- |
| `json-string` | `String` | no | JSON formatted text or Slab to parse |
| `target-type` | `Type` | no | Optional struct or compound type to hydrate into |

```tangu
(use /codec/json)
(let data (json/decode "{\"id\": 1, \"name\": \"Alice\"}"))
(assert-eq! (data :name) "Alice")
(use /codec/json)
(def User (Struct #Int id #String name))
(derive User From-JSON)
(let u (json/decode "{\"id\": 1, \"name\": \"Alice\"}" User))
```

### encode

`(json/encode expr) -> String`

Serializes a Tangu Map, List, Number, String, Boolean, or Struct instance into a JSON formatted string. Optional struct fields set to `()` serialize as null.

| Parameter | Type | Optional | Description |
| :--- | :--- | :--- | :--- |
| `expr` | `Any` | no | Data structure, Map, List, or Struct instance to serialize |

```tangu
(use /codec/json)
(let json-str (json/encode {:name "Bob" :scores [95 99]}))
```

### from-json

`(json/from-json Target-Type data) -> Target-Type`

Hydrates a decoded JSON Map or value into an instance of `Target-Type`, recursively converting nested struct fields, arrays, and optional fields.

| Parameter | Type | Optional | Description |
| :--- | :--- | :--- | :--- |
| `target-type` | `Type` | no | Struct or compound type descriptor |
| `data` | `Any` | no | Decoded JSON Map or value to hydrate |

```tangu
(use {From-JSON from-json} /codec/json)
(def Product (Struct #Int id #String title))
(derive Product From-JSON)
(let p (from-json Product {:id 42 :title "Book"}))
```
