Closed devarda closed 4 years ago
There is no ability to specify a full jsonpath for setting (though see #124 in case this may be a candidate for standardization).
However, if you can adapt your object of paths to move the final key and value into its own object, you can indicate arbitrary json paths leading up to the key:
it.only('Setting', function () {
const expected = {
age: 30,
email: 'abc@example.com',
'something_deeper': {
abc: 1,
quantity: 11
},
first_name: 'John',
last_name: 'Doe'
};
const givenPerson = {
age: 30,
email: 'abc@example.com',
// let's add first_name, last_name fields
'something_deeper': {
abc: 1
// let's add quantity here
}
};
// A two-level object of arbitrary JSON paths (minus the final key to modify) mapped to the key-values to modify
const obj1 = {
$: {
'first_name': 'John',
'last_name': 'Doe'
},
'$.something_deeper': {
quantity: 11
}
};
Object.entries(obj1).forEach(([path, valuesToSet]) => {
jsonpath({
json: givenPerson,
path,
wrap: false,
callback (obj) {
Object.entries(valuesToSet).forEach(([key, val]) => {
obj[key] = val;
});
}
});
});
const result = givenPerson;
assert.deepEqual(result, expected);
});
Closing as I think this should address, though feel free to comment further as needed.
I've had to implement my own reverse logic for a simple case like the following example. Are there any recommended approaches to
set
via JSON Path?