Tagscript

JSONVarParser

Turn a JSON payload into a variable with named fields.

json parses a JSON object and stores it under a name. Fields come back through the parameter, including nested ones through dotted paths. It pairs well with a parser that fetches a response body.

For template authors

Syntax

{json(name):{"key": "value"}}

Examples

{json(user):{"name":"Parbez","age":30}}Your age is {user(age)}.
# Your age is 30.

Reach nested fields with a dot:

{json(u):{"address":{"city":"Silchar"}}}You live in {u(address.city)}.
# You live in Silchar.

Any key starting with an underscore is refused and the tag is left as written:

{u(_secret)}
# {u(_secret)}

For developers

Register the parser

import { Interpreter, JSONVarParser, StrictVarsParser } from 'tagscript';
const ts = new Interpreter(new JSONVarParser(), new StrictVarsParser());

A variable parser is needed to read the result back.

Behaviour

Both the parameter and the payload are required. parse stores a SafeObjectTransformer on ctx.response.variables and returns an empty string.

The payload is JSON.parsed. Invalid JSON raises a TemplateError, so json was given something that is not valid JSON replaces the tag, the rest of the template still renders, and the error is on response.errors. Feed this tag output from a source you control, or wrap it in your own parser that validates first.

API reference

JSONVarParser

Last updated on

On this page

Edit on Github