Debian Codegraph @

docs/content/en/functions/transform/Unmarshal.md

raw
1 ---
2 title: transform.Unmarshal
3 description: Parses serialized data and returns a map or an array. Supports CSV, JSON, TOML, YAML, and XML.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: [unmarshal]
9 returnType: any
10 signatures: ['transform.Unmarshal [OPTIONS] INPUT']
11 aliases: [/functions/transform.unmarshal]
12 ---
13
14 The input can be a string or a [resource](g).
15
16 ## Options
17
18 The `transform.Unmarshal` function accepts an options map.
19
20 `delimiter`
21 : (`string`) Applicable to CSV files. The delimiter used. Default is `,`.
22
23 `comment`
24 : (`string`) Applicable to CSV files. The comment character used in the CSV. If set, lines beginning with the comment character without preceding whitespace are ignored.
25
26 `format`
27 : {{< new-in 0.149.0 />}}
28 : (`string`) The serialization format of the input, one of `csv`, `json`, `org`, `toml`, `xml`, or `yaml`. If empty or unspecified, Hugo infers the format from the input. For resources, this option is only needed if the file lacks an extension or to override the inferred format. For strings, it's only required when the format is ambiguous.
29
30 `lazyQuotes`
31 : (`bool`) Applicable to CSV files. Whether to allow a quote in an unquoted field, or to allow a non-doubled quote in a quoted field. Default is `false`.
32
33 `targetType`
34 : {{< new-in 0.146.7 />}}
35 : (`string`) Applicable to CSV files. The target data type, either `slice` or `map`. Default is `slice`.
36
37 ## Unmarshal a string
38
39 ```go-html-template
40 {{ $string := `
41 title: Les Misérables
42 author: Victor Hugo
43 `}}
44
45 {{ $book := transform.Unmarshal $string }}
46 {{ $book.title }} → Les Misérables
47 {{ $book.author }} → Victor Hugo
48 ```
49
50 ## Unmarshal a resource
51
52 Use the `transform.Unmarshal` function with global, page, and remote resources.
53
54 ### Global resource
55
56 A global resource is a file within the `assets` directory, or within any directory mounted to the `assets` directory.
57
58 ```tree
59 assets/
60 └── data/
61 └── books.json
62 ```
63
64 ```go-html-template
65 {{ $data := dict }}
66 {{ $path := "data/books.json" }}
67 {{ with resources.Get $path }}
68 {{ with . | transform.Unmarshal }}
69 {{ $data = . }}
70 {{ end }}
71 {{ else }}
72 {{ errorf "Unable to get global resource %q" $path }}
73 {{ end }}
74
75 {{ range where $data "author" "Victor Hugo" }}
76 {{ .title }} → Les Misérables
77 {{ end }}
78 ```
79
80 ### Page resource
81
82 A page resource is a file within a [page bundle][].
83
84 ```tree
85 content/
86 ├── post/
87 │ └── book-reviews/
88 │ ├── books.json
89 │ └── index.md
90 └── _index.md
91 ```
92
93 ```go-html-template
94 {{ $data := dict }}
95 {{ $path := "books.json" }}
96 {{ with .Resources.Get $path }}
97 {{ with . | transform.Unmarshal }}
98 {{ $data = . }}
99 {{ end }}
100 {{ else }}
101 {{ errorf "Unable to get page resource %q" $path }}
102 {{ end }}
103
104 {{ range where $data "author" "Victor Hugo" }}
105 {{ .title }} → Les Misérables
106 {{ end }}
107 ```
108
109 ### Remote resource
110
111 A remote resource is a file on a remote server, accessible via HTTP or HTTPS.
112
113 ```go-html-template
114 {{ $data := dict }}
115 {{ $url := "https://example.org/books.json" }}
116 {{ with try (resources.GetRemote $url) }}
117 {{ with .Err }}
118 {{ errorf "%s" . }}
119 {{ else with .Value }}
120 {{ $data = . | transform.Unmarshal }}
121 {{ else }}
122 {{ errorf "Unable to get remote resource %q" $url }}
123 {{ end }}
124 {{ end }}
125
126 {{ range where $data "author" "Victor Hugo" }}
127 {{ .title }} → Les Misérables
128 {{ end }}
129 ```
130
131 > [!NOTE]
132 > When retrieving remote data, a misconfigured server may send a response header with an incorrect [Content-Type][]. For example, the server may set the Content-Type header to `application/octet-stream` instead of `application/json`.
133 >
134 > In these cases, pass the resource `Content` through the `transform.Unmarshal` function instead of passing the resource itself. For example, in the above, do this instead:
135 >
136 > `{{ $data = .Content | transform.Unmarshal }}`
137
138 ## Working with CSV
139
140 The examples below use this CSV file:
141
142 ```csv
143 "name","type","breed","age"
144 "Spot","dog","Collie",3
145 "Rover","dog","Boxer",5
146 "Felix","cat","Calico",7
147 ```
148
149 To render an HTML table from a CSV file:
150
151 ```go-html-template
152 {{ $data := slice }}
153 {{ $file := "pets.csv" }}
154 {{ with or (.Resources.Get $file) (resources.Get $file) }}
155 {{ $opts := dict "targetType" "slice" }}
156 {{ $data = transform.Unmarshal $opts . }}
157 {{ end }}
158
159 {{ with $data }}
160 <table>
161 <thead>
162 <tr>
163 {{ range index . 0 }}
164 <th>{{ . }}</th>
165 {{ end }}
166 </tr>
167 </thead>
168 <tbody>
169 {{ range . | after 1 }}
170 <tr>
171 {{ range . }}
172 <td>{{ . }}</td>
173 {{ end }}
174 </tr>
175 {{ end }}
176 </tbody>
177 </table>
178 {{ end }}
179 ```
180
181 To extract a subset of the data, or to sort the data, unmarshal to a map instead of a slice:
182
183 ```go-html-template
184 {{ $data := dict }}
185 {{ $file := "pets.csv" }}
186 {{ with or (.Resources.Get $file) (resources.Get $file) }}
187 {{ $opts := dict "targetType" "map" }}
188 {{ $data = transform.Unmarshal $opts . }}
189 {{ end }}
190
191 {{ with sort (where $data "type" "dog") "name" "asc" }}
192 <table>
193 <thead>
194 <tr>
195 <th>name</th>
196 <th>type</th>
197 <th>breed</th>
198 <th>age</th>
199 </tr>
200 </thead>
201 <tbody>
202 {{ range . }}
203 <tr>
204 <td>{{ .name }}</td>
205 <td>{{ .type }}</td>
206 <td>{{ .breed }}</td>
207 <td>{{ .age }}</td>
208 </tr>
209 {{ end }}
210 </tbody>
211 </table>
212 {{ end }}
213 ```
214
215 ## Working with XML
216
217 When unmarshaling an XML file, do not include the root node when accessing data. For example, after unmarshaling the RSS feed below, access the feed title with `$data.channel.title`.
218
219 ```xml
220 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
221 <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
222 <channel>
223 <title>Books on Example Site</title>
224 <link>https://example.org/books/</link>
225 <description>Recent content in Books on Example Site</description>
226 <language>en-US</language>
227 <atom:link href="https://example.org/books/index.xml" rel="self" type="application/rss+xml" />
228 <item>
229 <title>The Hunchback of Notre Dame</title>
230 <description>Written by Victor Hugo</description>
231 <link>https://example.org/books/the-hunchback-of-notre-dame/</link>
232 <pubDate>Mon, 09 Oct 2023 09:27:12 -0700</pubDate>
233 <guid>https://example.org/books/the-hunchback-of-notre-dame/</guid>
234 </item>
235 <item>
236 <title>Les Misérables</title>
237 <description>Written by Victor Hugo</description>
238 <link>https://example.org/books/les-miserables/</link>
239 <pubDate>Mon, 09 Oct 2023 09:27:11 -0700</pubDate>
240 <guid>https://example.org/books/les-miserables/</guid>
241 </item>
242 </channel>
243 </rss>
244 ```
245
246 Get the remote data:
247
248 ```go-html-template
249 {{ $data := dict }}
250 {{ $url := "https://example.org/books/index.xml" }}
251 {{ with try (resources.GetRemote $url) }}
252 {{ with .Err }}
253 {{ errorf "%s" . }}
254 {{ else with .Value }}
255 {{ $data = . | transform.Unmarshal }}
256 {{ else }}
257 {{ errorf "Unable to get remote resource %q" $url }}
258 {{ end }}
259 {{ end }}
260 ```
261
262 Inspect the data structure:
263
264 ```go-html-template
265 <pre>{{ debug.Dump $data }}</pre>
266 ```
267
268 List the book titles:
269
270 ```go-html-template
271 {{ with $data.channel.item }}
272 <ul>
273 {{ range . }}
274 <li>{{ .title }}</li>
275 {{ end }}
276 </ul>
277 {{ end }}
278 ```
279
280 Hugo renders this to:
281
282 ```html
283 <ul>
284 <li>The Hunchback of Notre Dame</li>
285 <li>Les Misérables</li>
286 </ul>
287 ```
288
289 ### XML attributes and namespaces
290
291 Let's add a `lang` attribute to the `title` nodes of our RSS feed, and a namespaced node for the ISBN number:
292
293 ```xml
294 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
295 <rss version="2.0"
296 xmlns:atom="http://www.w3.org/2005/Atom"
297 xmlns:isbn="http://schemas.isbn.org/ns/1999/basic.dtd"
298 >
299 <channel>
300 <title>Books on Example Site</title>
301 <link>https://example.org/books/</link>
302 <description>Recent content in Books on Example Site</description>
303 <language>en-US</language>
304 <atom:link href="https://example.org/books/index.xml" rel="self" type="application/rss+xml" />
305 <item>
306 <title lang="en">The Hunchback of Notre Dame</title>
307 <description>Written by Victor Hugo</description>
308 <isbn:number>9780140443530</isbn:number>
309 <link>https://example.org/books/the-hunchback-of-notre-dame/</link>
310 <pubDate>Mon, 09 Oct 2023 09:27:12 -0700</pubDate>
311 <guid>https://example.org/books/the-hunchback-of-notre-dame/</guid>
312 </item>
313 <item>
314 <title lang="fr">Les Misérables</title>
315 <description>Written by Victor Hugo</description>
316 <isbn:number>9780451419439</isbn:number>
317 <link>https://example.org/books/les-miserables/</link>
318 <pubDate>Mon, 09 Oct 2023 09:27:11 -0700</pubDate>
319 <guid>https://example.org/books/les-miserables/</guid>
320 </item>
321 </channel>
322 </rss>
323 ```
324
325 After retrieving the remote data, inspect the data structure:
326
327 ```go-html-template
328 <pre>{{ debug.Dump $data }}</pre>
329 ```
330
331 Each item node looks like this:
332
333 ```json
334 {
335 "description": "Written by Victor Hugo",
336 "guid": "https://example.org/books/the-hunchback-of-notre-dame/",
337 "link": "https://example.org/books/the-hunchback-of-notre-dame/",
338 "number": "9780140443530",
339 "pubDate": "Mon, 09 Oct 2023 09:27:12 -0700",
340 "title": {
341 "#text": "The Hunchback of Notre Dame",
342 "-lang": "en"
343 }
344 }
345 ```
346
347 The title keys do not begin with an underscore or a letter---they are not valid [identifiers](g). Use the [`index`][] function to access the values:
348
349 ```go-html-template
350 {{ with $data.channel.item }}
351 <ul>
352 {{ range . }}
353 {{ $title := index .title "#text" }}
354 {{ $lang := index .title "-lang" }}
355 {{ $ISBN := .number }}
356 <li>{{ $title }} ({{ $lang }}) {{ $ISBN }}</li>
357 {{ end }}
358 </ul>
359 {{ end }}
360 ```
361
362 Hugo renders this to:
363
364 ```html
365 <ul>
366 <li>The Hunchback of Notre Dame (en) 9780140443530</li>
367 <li>Les Misérables (fr) 9780451419439</li>
368 </ul>
369 ```
370
371 [Content-Type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
372 [`index`]: /functions/collections/indexfunction/
373 [page bundle]: /content-management/page-bundles/