219 points · by selrond · 8y ago · 125 comments
JMESPath limitations:
- No simple if/else, but it is possible using a hack, documented below.
- The to_number function doesn't support boolean values, but it is possible using a hack, documented below.
- can't reference parents when doing iteration. Why? All options for iteration, [* ] and map, all use the iterated item as the context for any expression. There's no opportunity to get any other values in. May be possible for a fixed set of lengths. Something akin to the following (except there is no syntax for switching or if statements):
switch (length):
case 1: [expression[0]]
case 2: [expression[1], expression[1]]
case 3: [expression[0], expression[1], expression[2]]
...
- Key name can't come from an expression. Why? The ABNF for constructing key-value pairs is given as: keyval-expr = identifier ":" expression. The key is an identifier, which gives no possibility for making it an expression. No functions modify keys in such a way as to allow using an expression as a key.)- No basic math operations, add, multiply, divide, mod, etc. Why? Nobody added those operators/functions.
- There's a join, but no split.
- No array indexing based on expression. Why? Indexing is done based on a number or a slice expression, which also doesn't support expressions. Here's the ABNF:
bracket-specifier = "[" (number / "* " / slice-expression) "]" / "[]"
- No ability to group_by an expression.- No ability to get the index of an element in a list
Hacks:
Convert true/false to number:
boolean_expression && `1` || `0`
If/else:Option 1)
[{q:CONDITIONAL_EXPRESSION, v:IF_RESULT_EXPRESSION},{q:!COND_EXPRESSION,v:ELSE_RESULT_EXPRESSION}][?q]|[0].v
Option 2) {"if":CONDITIONAL_EXPRESSION, "ctx":@} | [{q:if ,v:ctx.IF_EXPRESSION},{q:!if,v:ctx.ELSE_EXPRESSION}][?q]|[0].vI then realized that using it in my code would make things much more declarative and easy to grok than a bunch of maps, filters etc. Here's a real example which I think illustrates it[1]. It has libraries for lots of languages with a clear specification/compliance test[2].
The cherry on the top is the interactive query on the website. You can tweak any of the examples (both queries and data) and get results instantly. Extremely useful for playing around, building queries to work with JSON data (webhooks, API responses etc)
[0] https://docs.aws.amazon.com/cli/latest/userguide/controlling...
[1] https://gist.github.com/gingerlime/757c7b4778c1ab68605dfce66...
[0] https://docs.aws.amazon.com/cli/latest/userguide/controlling...
I have been maintaining https://github.com/kislyuk/yq, which wraps jq with a transcoder for YAML and XML.
jmespath is more limited, but is well specified and easier to fit in your head. It's also much more appropriate for using as a library from other projects, since it has clean implementations in many languages. It's also an advantage in this case that it can't do everything, since you can more realistically provide untrusted user input.
jmespath's default (Go) CLI isn't as fully featured as jq, unfortunately.
I had never heard of jl before, but I've recently compiled an "awesome" collection of jq tools, libraries and use-cases at https://github.com/fiatjaf/awesome-jq that may be worth checking out.
I've also started using it just to get colorized/formatted output from curl or a local json file.
cat file.json | jqI love jq, and use it more often than JMESPATH. However, recently I've noticed that I arrive at "the solution" I need more quickly with JMESPATH.
In retrospect, JMESPATH's documentation and examples have been more useful for me than jq's (docs/examples).
The fact that a solution is treading familiar ground does not invalidate its utility.
In addition, arrays must be indicated clearly in JSON while you can consider children of an xml nodes to always form a list (be it empty or containing one element).
So while the two format are very similar, there is still some differences that doesn’t make them interchangeable for every usecase.
If there had been an opinionated SGML syntax which mapped directly and unambiguously to common language primitives and back, I'm sure it would have been more popular than JSON.
Though it seems like XSLT should support JSON:
As a simple example, there's no technical reason why XPath couldn't allow you to either use namespaces as written in the document[1] or ignore them when appropriate[2]. Nobody cared about usability and it's the number one reason I've heard why developers with jobs to do fled to JSON / YAML as quickly as possible. A similar story arises with XPath 2 — libxml2 never got support so that standard effectively doesn't exist for most projects, but there's no way to shift the resources away from developing further revisions which will also not be widely used towards much cheaper basic investment in shared infrastructure.
1. e.g. if the doc is <foo:bar>, it should never require you to write {http://path/to/foo}bar to match that element.
2. Ever try to target docs in multiple versions of a standard?
I don’t like js/json at all, but for json (and without much js knowledge) I can roll out simple validation in less time than is needed to understand these schema formats. If my structure is dynamic, omg it will be hard to explain it to declarative validator. If it contains value-level type logic (graphs, references), I bet second phase of validation by hand is inevitable anyway.
A second thing, full-blown xml is alien to any structures of simple languages and cannot be serialized like jsonlib.encode(foo). You create nodes, set attributes, build trees, all that mess. It feels like using a 17th century official mail ceremony to send “)))” to your buddy.
DTD was considered obsolete more than a decade ago.
Nobody uses anything but XSD nowadays.
Huh? Could have fooled me. In Cocoa, for example, serializing to JSON and serializing to an XML property list (or binary property list) is effectively the same code.
https://developer.apple.com/documentation/foundation/nsjsons...
https://developer.apple.com/documentation/foundation/nsprope...
see also: hating pascal's 'end' instead of '}' or claims that python is readable because it doesn't even have '}'
People shouldn't use JSON for anything hand-written. YAML or even the older INI format are way better suited for configuration files for one reason alone: they allow comments.
NIH claim is probably valid when there are no noticeable difference. In my opinion, XML differs a lot from JSON, particularly when one need to write snippets by hand. JSON also seems more logical/laconic (once upon a time M-expressions were supposed to come to stage, but S-expressions turned up to be good enough).
Partially yes, but it's also at least in part due to a "fuck all this language theory crap, lets just standardize something already" approach.
(Fair discloure: I'm a jq maintainer.)
Why do you need comments in a structure of nested - unique key mappings - arrays - strings - numbers - booleans - nulls ? You can include comments, just like any string, into it, just reserve a key with unique name, if you want. From JSON parser/transformer point of view, "comment" as a concept isn't a data structure piece, it's rather "intent" piece.
The "Web scale" is what MongoDB tried to sell (unfortunately, successfully), and it's not even close to being web scale.
Neither JSON schema or XML schema are particularly popular - and for good reason. Let's say you want to create a schema that limits field "country" to be limited to ISO 3166-1 country codes - either you:
* Keep that schema file updated by hand every time something like Sudan breaking in two happens (no).
* Write a program that generates the schema (seriously... no)
* Do schema validation in code where it belongs - pulling in relevant validation data from canonical sources, rather than some markup language invented by people who didn't have the imagination to consider a really common use case.
To your other point, however, dynamic code generation is becoming much more common. AWS generates a huge amount of its code from JSON definitions across multiple languages to keep its SDKs up to date. I could see schema validation being valuable in this domain as well.
There is. I find examples - snippets of XML/JSON - to be the best way of communicating this - not schema languages.
There is a lot of use for libraries dealing with time and dates. When you want to cover all cases, at some point you get to the situation when you have to allow variable number of seconds in a minute - not always 60, but sometimes 59 or 61, or may be even different numbers. And you don't know in advance - for arbitrary long future - which minutes will have which number of seconds.
So, for your timekeeping system to maintain precision, you have to allow external updates for when a minute will be considered non-60 seconds.
And those cases could happen more often than changing a list of valid country codes.
What would you do with time then?
Anyway, code:
yaml_text:
John: Yemen
James: South Sudan
python code: from strictyaml import load, MapPattern, Str, Enum
import pycountry
result = load(
yaml_text,
MapPattern(
Str(),
Enum([country.name for country in pycountry.countries]),
)
)
full disclosure: I wrote the validation library ^^ locations
.filter(l => l.state === 'WA')
.map(l => l.name)
.sort()
.join(', ')So you get reusability of queries across the stack, in all languages that implement a parser against the spec. Your example only provides re-usability in JavaScript, and requires evaluating code at run-time so may not be suitable for queries based on user-submitted data in multi-tenant environments.
In your opinion, where would someone be storing the json such that they'd benefit from a tool like this? The only time I use json outside of pulling it from an API (where I can convert it to a native object) is probably storing it in postgres, where I've already got json querying tools.
- Infrastructure configuration stored in JSON. Query could reference other JSON files, or the JSON file itself (loops would need to be considered).
- Declarative reactive programming, e.g. platforms like IFTT. You might want to take certain actions based on data in a JSON post. The IFTT GUI would create JSON config files that its server side parsers can safely use without eval'ing code to decide which action to take.
- Adding conditional logic to jsonschema form generation. Recently I've built a questionnaire renderer in react that renders forms based on jsonschema. The user creates forms with a GUI, which compiles them to JSON, and then the renderer knows how to render. Conditional logic (e.g. question B is required if question A === true) can be quite limited when constrained to pure JSON. Something like this could help with that.
The nice thing about declarative syntax is you can build a GUI to generate it, so users never use the JSON itself, but you can store it in a database, safely execute rules based on it, etc. without requiring programming from the user.
That said, there are usually better ways to accomplish this, like in pure JSON for example. Mongo syntax achieved this, with declarative operators like $or{}, ${sum}, etc., but it can be quite cumbersome.
In at least some languages if these queries can be used without deserializing into a native data structure and then serialized back into a string, this could be a major win.
https://www.couchbase.com/products/n1ql
It's not standalone though, you need Couchbase to use it.
The reason I am asking is that I am currently trying to build a tool to analyze a kind of time series data, think log file entries, in order to look for anomalies and visualize them. I could of course just build all the transformations I am interested in in an ad hoc fashion but it would be nice to have a mathematical framework in order to start out with a small set of basic operations and then compose those while having some guarantees about the expressiveness of that the basic operations and ideally also a rigorous foundation for transforming them, for example for performance optimizations.
But so far I was unable to find something that seems fitting, everything I am aware of is either to limited like relational algebra or way to general like general functions. It feels like what I am looking for should exist but I am unable to find it.
The other thing is that SQL seems not the best fit to me. Say you just want to know how many events occurred in the last three months in any hour, that is straight forward grouping and counting at first, but already rounding the timestamps to an hour is not as obvious as it should be. But if there was no event in a specific hour, your result will just have no row for that hour instead of a row saying there were zero events in that hour. This in turn will cause more trouble if you want to build a histogram showing in how many hours there were say 0 to 9, 10 to 19, 20 to 29, and so on events. Certainly still doable with SQL but we are already entering the territory where writing a single query will take most people several hours to get the desired result.
I also couldn't easily tell how to express calculating the 99th percentile of the event size for every day of the week and hour of the day. I am pretty sure it is possible but I guess it would also be pretty unreadable unless you put in quite a bit of effort to create utility functions instead of hacking together one huge SQL statement. Then again I don't really know much about the more recent SQL features for partitioning and aggregating, maybe I should have a closer look at that first.
All of what you have just described isnt very hard in SQL.. coalescing on null, aggregating, etc.
GROUPING SETS() will give you your missing rows.
Very simple standard and easy to implement, but not as powerful as jmespath nor jq.
https://ci.mines-stetienne.fr/sparql-generate/playground.htm...
The "evaluation of sub-expressions" made me curious. This line:
token.func = Function('_,i,args', 'return ' + token.val);
..could be a potential security issue with user-submitted expressions? var name = one(users, '[_.id==?].name', 123)
uses parameterized queries, same idea as with SQL to eliminate injections.Might be useful if you are testing API or playing with JSON data.
But this time it's different?
sort(@)
I'm like nope! What is this "@" symbol? Why can't that be "name"? I'm already passing judgment that this library will be a nightmare to use which isn't good.
Now I know I can read the docs and eventually what I can pass the sort expression and what it all means, however, this is an issue I come across more and more with new libraries in programming... show simple examples, not "smart" or complicated ones. I shouldn't have to read through docs to try to decipher an introductory example. There is a reason every programming language starts with "Hello World".
For last 3 - 4 years I see lots of AWS CLI examples piping through jq. That’s an extra dependency that’s not necessary when this is built in.
Here’s the author’s idea of intro materials (posted Jan 2015):
http://jamesls.com/how-to-easily-explore-jmespath-on-the-com...
I’ve found him very responsive on bugs and (provably useful) feature ideas.
X | Y | Z
The @ is the result from the prior transform.
I would've preferred _ from scala, but meh.
[.locations[] | select(.state == "WA").name] | sort | join(", ") | { WashingtonCities: . }