# 12.8 JSON

> `parseJson` turns a JSON text into a value you can walk through, and `jsonText` goes the other way.

Web page: https://pseudolearn.app/en/spec/biblioteca/json

> **In one sentence**
>
> `parseJson` turns a JSON text into a value you can walk through, and `jsonText` goes the other way.

## 12.8.1 How it works

`parseJson(text)` returns a `Result`: `Success` with a `JsonValue`, or `Error` with a `JsonError` saying what failed and where. On a `JsonValue` you can ask:

| Operation | Returns |
| --- | --- |
| `v.kind()` | what kind of value it is: object, array, text, number, boolean or null |
| `v.field(key)` | `Something(value)` or `Nothing` |
| `v.element(i)` | `Something(value)` or `Nothing`, with indices from zero |
| `v.keys()`, `v.length()` | the keys in their original order; how many elements |
| `asInteger`, `asReal`, `asText`, `asBoolean` | `Something` if the value is of that type |

**Figure 12.8-1: JSON tree**

An object with three fields: nombre with "Ana", edad with 15 and notas with an array of 7 and 9. field("edad") goes down to 15.

The JSON text and the tree of values `parseJson` produces. `field` and `element` go down the tree.

### Program: Reading a record card

```pseudolearn
Algorithm Ficha
  Switch parseJson('{"nombre": "Ana", "edad": 15, "notas": [7, 9]}') Do
    Success(ficha):
      Write ficha.keys(), " ", ficha.length();
      Switch ficha.field("edad") Do
        Some(edad): Write "edad: ", jsonText(edad);
        None: Write "sin edad";
      EndSwitch
      Write jsonText(ficha);
    Failure(problema):
      Write problema.code;
  EndSwitch
EndAlgorithm
```

**Output**

```text
["nombre", "edad", "notas"] 3
edad: 15
{"nombre":"Ana","edad":15,"notas":[7,9]}
```

*The program finishes normally.*

`jsonText` writes compact JSON, keeps the order of keys and the original text of numbers. Parsing what it writes gives back the same value.

Parsing is **strict**: no comments, no trailing commas, no repeated keys. The error gives the line and column where it was detected:

### Program: One comma too many

```pseudolearn
Algorithm Roto
  Switch parseJson('{"edad": 15,}') Do
    Success(ficha): Write jsonText(ficha);
    Failure(problema):
      Define codigo As JsonErrorCode <- problema.code;
      Write codigo, " en ", problema.jsonLine, ":", problema.jsonColumn;
  EndSwitch
EndAlgorithm
```

**Output**

```text
InvalidSyntax en 1:13
```

*The program finishes normally.*

The values of `JsonKind` and `JsonErrorCode` are these:

| `JsonKind` | `JsonErrorCode` |
| --- | --- |
| `JsonKind.Object`, `JsonKind.Array` | `JsonErrorCode.InvalidSyntax` |
| `JsonKind.JsonStringKind`, `JsonKind.JsonNumber` | `JsonErrorCode.UnexpectedEnd`, `JsonErrorCode.TrailingContent` |
| `JsonKind.JsonBoolean`, `JsonKind.Null` | `JsonErrorCode.InvalidEscape`, `JsonErrorCode.DuplicateKey`, `JsonErrorCode.DepthExceeded` |

> **Limit**
>
> - Nesting depth is limited by the host, 64 by default: exceeding it is `ProfundidadExcedida`.
> - Repeated keys are `ClaveDuplicada`.
> - There is no equality between JSON values: compare their texts.

**In short**
- `parseJson` returns a value or an error with a position.
- `field`, `element` and `as…` return `Optional`.
- `jsonText` writes compact JSON that can be read back.

**See also**
- [12.7 Files and folders](https://pseudolearn.app/en/spec/biblioteca/archivos.md)
- [3.10 Optional and Result](https://pseudolearn.app/en/spec/tipos/opcional-resultado.md)
