Eduardo Uribe

April 26, 2022

JSON.stringify() with Nunjucks built-in "dump" filter

We can use the Nunjucks dump filter to call JSON.stringify on an object and "dump" the result(s) into our template.

For example, we can view information about our current page with the Eleventy supplied page variable.

If we try to output the page variable directly, it renders [object Object].

{{ page }}

# Outputs:
[object Object]

But using Nunjucks dump filter on the page variable outputs the object as a JSON string.

{{ page | dump }} 

# Outputs the Eleventy provided `page` data as a string
{
"date": "2022-04-26T00:00:00.000Z",
"inputPath": "./private/pages/blog/posts/json-stringify-with-nunjucks-dump-filter.md",
"fileSlug": "json-stringify-with-nunjucks-dump-filter",
"filePathStem": "/pages/blog/posts/json-stringify-with-nunjucks-dump-filter",
"outputFileExtension": "html",
"templateSyntax": "njk,md",
"url": "/blog/json-stringify-with-nunjucks-dump-filter/",
"outputPath": "_public/blog/json-stringify-with-nunjucks-dump-filter/index.html"
}

... Cool, now we know.