使用 JSONPath-plus 构建对象

问题描述 投票:0回答:1

是否可以使用 JSONPath-plus 从空对象开始构建对象?

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)

预期产出

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

输出

{}
javascript jsonpath jsonpath-plus
1个回答
0
投票

是的,可以使用 JSONPath-plus 从空对象开始构建对象。但是,您需要处理父对象尚不存在的情况。以下是如何修改代码以实现预期输出:

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);

这将产生预期的输出:

{
  "book": {
    "author": "Foo Bar"
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.