Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Javascript JSON object properties with XPath style [closed]

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.

like image 832
kasey Avatar asked Sep 05 '25 03:09

kasey


1 Answers

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);
like image 90
Sitian Liu Avatar answered Sep 07 '25 21:09

Sitian Liu