jsonpath-template

1.1.0 • Public • Published

jsonpath-template

String template library inspired by both jsonpath and string-template projects

Uses jsonpath to provide the path handling. Kept as simple as possible - so no template loading or caching from files.

License Build Status Coverage Status David npm npm node

Usage

Basic usage is as below:-

const jpt = require('jsonpath-template');
var tplString = "Hello there {$.person.name}, isn't it a {$.daytype} day?";
var json = {person:{name:"Adam"},daytype: "nice"};
var template = new jpt(tplString);
console.log(template.apply(json));

This produces:-

Hello there Adam, isn't is a nice day?

You can also specify custom start and end tags:-

const jpt = require('jsonpath-template');
var tplString = "Hello there [[$.person.name]], isn't it a [[$.daytype]] day?";
var json = {person:{name:"Adam"},daytype: "nice"};
var template = new jpt(tplString);
console.log(template.tags("[[","]]").apply(json));

Which produces the same output as the first example. Note that you can chain tags and apply, for convenience.

As jsonpath is used for path handling you shouldn't use any tag values that can be found within a jsonpath. An example of this would be single quote characters, or dollar signs, or single square brackets. Double of each of these should be fine, as in the above example.

Any jsonpath suported by the jsonpath library is valid. So for example, the following template string would work with the last example:-

var tplString = "Hello there [[$['person'].name]], isn't it a [[$.daytype]] day?";

License and Copyright

Copyright Adam Fowler 2019-2023. License is MIT.

Package Sidebar

Install

npm i jsonpath-template

Weekly Downloads

0

Version

1.1.0

License

MIT

Unpacked Size

8.14 kB

Total Files

7

Last publish

Collaborators

  • adamfowleruk