Search code examples
jsonjsonpath

Add string literal into JSONPath output


Can I add a string literal to a JSONPath selector?

{ "items": [
    { "x": 1 },
    { "x": 2 },
    { "x": 3 },
    { "x": 4 }]
}

$.items[:].x gives...

[
  1,
  2,
  3,
  4
]

For example, can I make it return...

[
  { 1 },
  { 2 },
  { 3 },
  { 4 }
]

I want to generate some code that adds items to a dictionary.


Solution

  • As discussed in the comments, this cannot be done using JSONPath (alone) since a path query returns only valid JSON and the target format is not valid. In general, JSONPath is not the right tool here, a JSON transformation using a library like Jolt would be more appropriate; but again, similar to XSLT transformations, we can only create valid output. So, as you already have found out, you would need to use string functions to mingle the code as needed. For instance, a regex substitution could do:

    const regex = /(\d+),?/gm;
    const str = `[
      1,
      2,
      3,
      4
    ]`;
    const subst = `{ $1 },`;
    
    // The substituted value will be contained in the result variable
    const result = str.replace(regex, subst);
    
    console.log('Substitution result: ', result);