Debian Codegraph @

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

raw
1 ---
2 title: transform.Unmarshal
3 description: Returns a map or an array parsed from serialized data in CSV, JSON, TOML, YAML, or XML format.
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. Hugo caches the result, so calling the function multiple times with the same resource incurs no additional overhead.
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 A CSV file is tabular, so unlike JSON, TOML, XML, and YAML, `transform.Unmarshal` always returns a collection with one entry per row instead of a single object. This is a slice of rows by default, or a slice of row maps when you set `targetType` to `map`.
141
142 The examples below use this CSV file:
143
144 ```csv
145 "name","type","breed","age"
146 "Spot","dog","Collie",3
147 "Rover","dog","Boxer",5
148 "Felix","cat","Calico",7
149 ```
150
151 To render an HTML table from a CSV file:
152
153 ```go-html-template
154 {{ $data := slice }}
155 {{ $file := "pets.csv" }}
156 {{ with or (.Resources.Get $file) (resources.Get $file) }}
157 {{ $opts := dict "targetType" "slice" }}
158 {{ $data = transform.Unmarshal $opts . }}
159 {{ end }}
160
161 {{ with $data }}
162 <table>
163 <thead>
164 <tr>
165 {{ range index . 0 }}
166 <th>{{ . }}</th>
167 {{ end }}
168 </tr>
169 </thead>
170 <tbody>
171 {{ range . | after 1 }}
172 <tr>
173 {{ range . }}
174 <td>{{ . }}</td>
175 {{ end }}
176 </tr>
177 {{ end }}
178 </tbody>
179 </table>
180 {{ end }}
181 ```
182
183 To extract a subset of the data, or to sort the data, unmarshal to a map instead of a slice:
184
185 ```go-html-template
186 {{ $data := dict }}
187 {{ $file := "pets.csv" }}
188 {{ with or (.Resources.Get $file) (resources.Get $file) }}
189 {{ $opts := dict "targetType" "map" }}
190 {{ $data = transform.Unmarshal $opts . }}
191 {{ end }}
192
193 {{ with sort (where $data "type" "dog") "name" "asc" }}
194 <table>
195 <thead>
196 <tr>
197 <th>name</th>
198 <th>type</th>
199 <th>breed</th>
200 <th>age</th>
201 </tr>
202 </thead>
203 <tbody>
204 {{ range . }}
205 <tr>
206 <td>{{ .name }}</td>
207 <td>{{ .type }}</td>
208 <td>{{ .breed }}</td>
209 <td>{{ .age }}</td>
210 </tr>
211 {{ end }}
212 </tbody>
213 </table>
214 {{ end }}
215 ```
216
217 ## Working with XML
218
219 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`.
220
221 ```xml
222 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
223 <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
224 <channel>
225 <title>Books on Example Site</title>
226 <link>https://example.org/books/</link>
227 <description>Recent content in Books on Example Site</description>
228 <language>en-US</language>
229 <atom:link href="https://example.org/books/index.xml" rel="self" type="application/rss+xml" />
230 <item>
231 <title>The Hunchback of Notre Dame</title>
232 <description>Written by Victor Hugo</description>
233 <link>https://example.org/books/the-hunchback-of-notre-dame/</link>
234 <pubDate>Mon, 09 Oct 2023 09:27:12 -0700</pubDate>
235 <guid>https://example.org/books/the-hunchback-of-notre-dame/</guid>
236 </item>
237 <item>
238 <title>Les Misérables</title>
239 <description>Written by Victor Hugo</description>
240 <link>https://example.org/books/les-miserables/</link>
241 <pubDate>Mon, 09 Oct 2023 09:27:11 -0700</pubDate>
242 <guid>https://example.org/books/les-miserables/</guid>
243 </item>
244 </channel>
245 </rss>
246 ```
247
248 Get the remote data:
249
250 ```go-html-template
251 {{ $data := dict }}
252 {{ $url := "https://example.org/books/index.xml" }}
253 {{ with try (resources.GetRemote $url) }}
254 {{ with .Err }}
255 {{ errorf "%s" . }}
256 {{ else with .Value }}
257 {{ $data = . | transform.Unmarshal }}
258 {{ else }}
259 {{ errorf "Unable to get remote resource %q" $url }}
260 {{ end }}
261 {{ end }}
262 ```
263
264 Inspect the data structure:
265
266 ```go-html-template
267 <pre>{{ debug.Dump $data }}</pre>
268 ```
269
270 List the book titles:
271
272 ```go-html-template
273 {{ with $data.channel.item }}
274 <ul>
275 {{ range . }}
276 <li>{{ .title }}</li>
277 {{ end }}
278 </ul>
279 {{ end }}
280 ```
281
282 Hugo renders this to:
283
284 ```html
285 <ul>
286 <li>The Hunchback of Notre Dame</li>
287 <li>Les Misérables</li>
288 </ul>
289 ```
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/