I have a Java script Object and I need to dynamically read, write and delete values based on the JSONPath
.
Is there a library for JavaScript?
I know that there is jsonpath.js but this is only to fetch a value or an object based on the JSONPath
. Please help.
An example:
Suppose I have this JavaScript object
var someData = {
store: {
book: [{
category: "fiction",
author: "Herman Melville",
title: "Moby Dick",
isbn: "0-553-21311-3",
price: 8.99
}, {
category: "fiction",
author: "some Author"
title: "The Lord of the Rings",
isbn: "0-395-19395-8",
price: 22.99
}],
}
}
and I have a JSONPath = $.store.book[0].author
this JSONPath
varies every time.
so this JSONPath
points to the author named Herman Melville
lets us say the value to be replaced is "name2" how do I do it dynamically.
and the worst case comes here
If the JSONPath = $.store.book[*].author
see that 0 is replaced by * this means that it points to all the authors in the array book.
So I should be able to read and write the author name.
jsonpath.js does the read function but not anything else.
Please comment if I am not clear.
you can try something like https://lodash.com/docs#set
here is an example:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
lodash.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With