4 ms·
I think I'm missing something here, because I can achieve the same using normal js stuff = { "author": { "name": { "first": "Lloyd",
by cubicle67 15y ago
I think I'm missing something here, because I can achieve the same using normal js
stuff = {
"author": {
"name": {
"first": "Lloyd",
"last": "Hilaiel"
},
"drinkPref": [
"whiskey",
"beer",
"wine"
],
},
"thing": "JSONSelect site",
"license": "(cc) BY-SA"
}
stuff.author.drinkPref[0]
> "whiskey"
- bitanarch 15y agoBut selecting a list of similar items in plain JavaScript would be troublesome.
- kalleboo 15y agoTheir site has a pretty bad example. Instead imagine it's an array of authors instead. Then their selector would give you a list of all their favourite drinks, which would require a loop in normal JS. I think I'd prefer something more XPath-like than CSS myself (as someone linked in another comment)
- sambeau 15y agoI'd love to see a javascript+json version of xquery. It would rock as a templating language. Naming it might be tricky though.
- riffraff 15y agothere is a minimal spec, and implementations, of JSONPath, which may be enough for you
- alinajaf 15y agoCouldn't this be done with a simple map function? Not sure the exact javascript but in ruby it would be as simple as: favourite_drinks = authors.map { |a| a[:favourite_drink] } Internally I'd imagine the language will have to loop through the json anyway. Are there any other benefits I'm missing (apart from of course the nice css-like syntax, which is perfectly valid).
- Groxx 15y agoIt could be, yes. `map` isn't built-in on all browsers, though, which I think has hurt its use. i.e., most people don't think about it, so it doesn't get used as often.
- subbu 15y agoUnderscore.js and Prototype.js both define this function. You can include this and use map. Underscore delegates it to ECMAScript 5's native map if available.
- Groxx 15y agoIt's definitely 'out there', and you can always just copy-paste to get the same code and delegation[1], but the lack of default availability is a pretty damaging blow. It shouldn't be, but the Javascript world isn't exactly a pantheon of high-quality code. [1]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en/JavaScript/Reference/Global...
- aquark 15y agoBut what happens in the case where there is no author element? With normal javascript you would get an exception .. hopefully with this you just get back undefined without having to check every step in the path.
- lloydhilaiel 15y agowith the reference implementation: JSONSelect.match(".nonexistantkey .somechild", obj) returns [] Alternately, if you use the JSONSelect.forEach() method your callback will just not be invoked. So no existence testing before access for recursive values. A main benefit of this thing in javascript.