javascriptjsonpathjsonpath-plus

Build a object with JSONPath-plus


Is it possible use JSONPath-plus for build an object starting from empty object?

EG:

const data = {}; // start from empty object

const updater = (cb: (value: string) => string): JSONPathCallback => (value, _, { parent, parentProperty }) => {
    parent[parentProperty] = cb(value);
   return parent;
}
// add in book object author name Foo Bar
const r = JSONPath({
    path: '$.book.author',
    json: data,
   callback: updater(() => 'Foo Bar'),
});
console.log(data)

expected output

{
  book: {
    author: 'Foo Bar'
  }
}

output

{}

Solution

  • Yes, it's possible to use JSONPath-plus to build an object starting from an empty object. However, you need to handle the case where the parent objects don't exist yet. Here's how you can modify your code to achieve the expected output:

    const data = {}; // start from empty object
    
    const updater = (cb) => (value, _, { parent, parentProperty }) => {
        if (!parent[parentProperty]) {
            parent[parentProperty] = {};
        }
        parent[parentProperty] = cb(value);
        return parent;
    }
    
    const r = JSONPath({
        path: '$.book.author',
        json: data,
        callback: updater(() => 'Foo Bar'),
    });
    
    console.log(data);
    

    This will produce the expected output:

    {
      "book": {
        "author": "Foo Bar"
      }
    }