jmespath / jmespath.jep

Proposals for extending the JMESPath Language.
8 stars 5 forks source link

Function proposal - format() #1

Open glenveegee opened 4 years ago

glenveegee commented 4 years ago

Given a template and either an array or object output a string interpolated with values:

For example in Javascript one might implement it as follows:

registerFunction(
  'format',
  ([template, templateStringsMap]) => {
    let newTemplate = template;
    for (const attr in templateStringsMap) {
      const rgx = new RegExp(`\\$\\{${attr}\\}`, 'g');
      newTemplate = newTemplate.replace(rgx, templateStringsMap[attr] ?? '');
    }
    return newTemplate;
  },
  [{ types: [TYPE_STRING] }, { types: [TYPE_OBJECT, TYPE_ARRAY] }],
);

Examples:

// With ARRAY input:
jmespath.search(
    [1,"2", null, ["a", 2, "foo"], {b: "z"}, true, false],
    "format4('${0} | ${1} | ${2} | ${3} | ${4} | ${5} | ${6} | ${7}', @)"
)
// OUTPUTS: '1 | 2 | null | a,2,foo | [object Object] | true | false | ${7}'
// With **OBJECT** input:
jmespath.search(
    {foo: 'FOO', bar: null},
    "format4('${foo} | ${bar} | ${baz}', @)"
);
// OUTPUTS: 'FOO | null | 12 | ${baz}'