I tried this for 2 days but can’t figure it out in any way.
This is my JSON:
{
"items": [
{
"name":"itemA",
"bins":[
{
"bin_id":"b1",
"count":"11"
},
{
"bin_id":"b2",
"count":"22"
}
]
},
{
"name":"itemB",
"bins":[
{
"bin_id":"b5",
"count":"55"
}
]
}
]
}
Important note. Input JSON could be empty object ‘{}’ or missing any part of the hierarchy.
I need to insert whole hierary or update final entry for "count". My input arguments are: itemName, binId and new count.
So for "itemA", "b1" and count 68. I need to set .items -> (item with name: "itemA") -> (bin with bin_id 68) -> count = 68.
I tried using INDEX to access items. And that works… but I can’t seem to further access bins and update final count.
UPDATE:
I got something like this:
.items |= [INDEX(.[]?;.name) | .itemA |= .+ {name:"itemA",bins:[INDEX(.bins[]?;.bin_id) | .b1 |= .+ {bin_id:"b1",count:"188000"} | .[]]} | .[]]
But it does look ugly. Can this be done more clearly?
2
Answers
Given these arguments, this is the adapted, now nested approach from the previous question:
Demo
Which can be generalized by moving the repeating code into a function, and nesting the calls:
Demo
Both output:
You can use
select
to get the object to update :