File: json.md

package info (click to toggle)
liquidsoap 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,372 kB
  • sloc: ml: 71,806; javascript: 27,320; ansic: 398; xml: 114; sh: 99; lisp: 96; makefile: 26
file content (308 lines) | stat: -rw-r--r-- 7,045 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
## 📦 Working with JSON in Liquidsoap

Liquidsoap makes it easy—and safe—to work with JSON data directly in your scripts. Whether you're loading configuration files, interfacing with APIs, or managing playlist metadata, JSON is a powerful format to master.

This page walks you through how JSON parsing works in Liquidsoap, how type safety is enforced, and how to use advanced features like nullable types, custom keys, and associative object parsing.

Let’s start simple and build progressively toward the more advanced features. 🧗

### 🔹 Getting Started: Parsing a Simple JSON Object

You can parse a JSON string using the special `let json.parse` syntax:

```liquidsoap
let json.parse v = '{"foo": "abc"}'
print("We parsed a JSON object and got value " ^ v.foo ^ " for attribute foo!")
```

✅ Output:

```
We parsed a JSON object and got value abc for attribute foo!
```

What's happening here?

Liquidsoap watches how you use `v.foo` (as a string), and it _checks at runtime_ that the JSON contains `"foo"` and that its value is indeed a string. If there's a mismatch, you'll get a clear error.

Example with incorrect type:

```liquidsoap
let json.parse v = '{"foo": 123}'
```

⛔ Raises:

```
Error 14: Uncaught runtime error:
type: json,
message: "Parsing error: json value cannot be parsed as type {foo: string, _}"
```

### 📁 Loading JSON from Files

Instead of hardcoding JSON as a string, you can load it from a file:

```liquidsoap
let json.parse v = file.contents("/path/to/file.json")
```

Let’s look at a realistic example. Suppose you’re parsing a `package.json` file from an npm package:

```liquidsoap
let json.parse package = file.contents("/path/to/package.json")

name = package.name
version = package.version
test = package.scripts.test

print("This is package " ^ name ^ ", version " ^ version ^ " with test script: " ^ test)
```

### ✅ Use Type Annotations for Reliable Parsing

Sometimes Liquidsoap can’t infer types correctly—especially when you use variables only inside string interpolations (`#{...}`). In those cases, values default to `null`, which might be confusing.

The solution: add an **explicit type annotation** to your parse statement. The type annotation is then used to drive the parser and pick the json data that you are expecting:

```liquidsoap
let json.parse ({
  name,
  version,
  scripts = {
    test
  }
} : {
  name: string,
  version: string,
  scripts: {
    test: string
  }
}) = file.contents("/path/to/package.json")
```

Now everything works as expected—even if you only reference variables inside interpolations.

## 🧩 Understanding JSON Type Annotations

Liquidsoap’s JSON parser uses a rich type system that maps onto JSON’s structure. Let’s break it down:

### **🔤 Ground Types**

| Type     | Description                  | Example value     |
| -------- | ---------------------------- | ----------------- |
| `string` | A sequence of characters     | `"hello"`         |
| `int`    | An integer                   | `42`              |
| `float`  | A number, including decimals | `3.14` or `123.0` |

Liquidsoap will coerce integers into floats if needed (e.g. `123` can be a `float`).

### **❓ Nullable Types**

Add `?` to make a type optional:

```liquidsoap
test: string?  # test is either a string or null
```

Useful when parsing data that may or may not include a field:

```liquidsoap
let json.parse ({
  scripts
} : {
  scripts: {
    test: string?
  }?
}) = file.contents("package.json")
```

You can check for presence using:

```liquidsoap
# Option 1: Explicit check
test =
  if null.defined(scripts) then
    null.get(scripts.test)
  else
    null()
  end

# Option 2: Fallback value
test = (scripts ?? { test = null }).test
```

---

### **🔗 Tuples**

Tuples parse fixed-size arrays with specific types for each position:

```liquidsoap
(int * float * string)
```

This parses a JSON array like `[1, 2.5, "hello"]`.

Use `_` as a wildcard to ignore types you don’t care about:

```liquidsoap
(_ * _ * float)  # Only the third element must be a float
```

---

### **📋 Lists**

To parse a JSON array of values of the same type, use brackets:

```liquidsoap
[int]     # list of integers
[float?]  # list of optional floats
```

Example:

```json
[44.0, 55, 66.12]
```

Can be parsed as: `[float]`

### **🧱 Objects (Records)**

Use `{...}` to parse JSON objects into named fields:

```liquidsoap
{foo: int, bar: string}
```

This tells Liquidsoap to extract only the fields you care about. Extra fields in the JSON are ignored.

### 🏷️ **Custom JSON Keys**

JSON keys often contain characters or spaces that aren't valid Liquidsoap variable names.

You can map them like this:

```liquidsoap
{"foo bar" as foo_bar: int}
```

Example:

```json
{ "foo bar": 123 }
```

Liquidsoap parses this as a variable `foo_bar = 123`.

### 🗂️ **Associative Objects as Lists**

What if you don’t know the keys in advance?

Use `[(string * < value type>)] as json.object` to treat an object like a list of key-value pairs.

Example JSON:

```json
{ "a": 1, "b": 2, "c": 3 }
```

Use this type:

```liquidsoap
[(string * int)] as json.object
```

Parsed as:

```liquidsoap
[("a", 1), ("b", 2), ("c", 3)]
```

You can even use `int?` if some values might be missing or of a non-int type.

### ⚠️ Handling Errors

Parsing errors raise a `error.json` exception:

```liquidsoap
try
  let json.parse ({status, data = {track}} : {...}) = response
  # Do something with data
catch err: [error.json] do
  # Handle the parse failure
end
```

---

## 🧪 Full Example

```liquidsoap
data = '{
  "foo": 34.24,
  "gni gno": true,
  "nested": {
    "tuple": [123, 3.14, false],
    "list":  [44.0, 55, 66.12],
    "nullable_list": [12.33, 23, "aabb"],
    "object_as_list": {
      "foo": 123,
      "gni": 456.0,
      "gno": 3.14
    },
    "arbitrary object key ✨": true
  }
}'

let json.parse (x :
  {
    foo: float,
    "gni gno" as gni_gno: bool,
    nested: {
      tuple: (_ * float),
      list: [float],
      nullable_list: [int?],
      object_as_list: [(string * float)] as json.object,
      "arbitrary object key ✨" as arbitrary_key: bool,
      not_present: bool?
    }
  }
) = data
```

### 🛠️ Other Features

- **JSON5 support** (for trailing commas, comments, etc.):

```liquidsoap
let json.parse[json5=true] x = ...
```

- **Exporting to JSON**:

```liquidsoap
print(json.stringify({artist="Bla", title="Blo"}))
```

- **Building JSON manually**:

This can be useful when dynamically generating json output:

```liquidsoap
j = json()
j.add("foo", 1)
j.add("bar", "baz")
j.remove("foo")
print(json.stringify(j))
```

## 🚀 Recap

✅ Liquidsoap gives you a safe and expressive way to work with JSON
🧠 Type annotations help catch issues early and make your code clearer
🛠️ Advanced types let you tackle real-world data with ease

Once you’ve got the hang of parsing, try exploring the actual `tests/language/json.liq` test file in the source repo—it's full of neat examples and tricks!