Hacker News new | ask | show | jobs
by sbarre 779 days ago
All these examples assume an understanding ahead of time of your data structure.

Can you write examples in Python and Javascript where you'd extract those titles from an arbitrary JSON structure? ;-)

3 comments

I tried this once, and I accidentally invented a poorly implemented and incomplete version of Lisp.
> 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.
You mean searching for keys?

  $..book[?@.price<10].title
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).map(x=>x.title)