> All these examples assume an understanding ahead of time of your data structure.
How would one use JSONPath to extract all book titles from an arbitrary JSON structure?
Also, when might that use case apply? I can't think of when I've ever needed to do something like this, but I'm interested in learning. :)
JSONPath has excellent documentation, you can absolutely answer that question for yourself very easily.
I tried this once, and I accidentally invented a poorly implemented and incomplete version of Lisp.
Re:How to Use JSON Path
by Silphendio on Friday May 03, 2024 @07:47AM
(#40246565)
You mean searching for keys?
$..book[[email protected]<10]
Yeah, I don't think javascript has that function in the standard library. Writing one is not super complicated, but having to put that into every file (or importing it) is not ideal. find_key = (data, key) => {
if(data instanceof Array){
return data.map(x=>find_key(x, key)).flat()
}
if(data instanceof Object){
let res = Object.keys(data).map(x=>find_key(data[x], key))
if(data.hasOwnProperty(key)){
res.push(data[key])
}
return res.flat()
}
return []
}
find_key(data, "book").filter(x=>x.price < 10)
Can you write examples in Python and Javascript where you'd extract those titles from an arbitrary JSON structure? ;-)