3 ms·
I felt this pain when working with JSON APIs. I ended up writing my own literate JSON spec tool that looked like JSON but was in fact Python: {"name": str
by willvarfar 10y ago
I felt this pain when working with JSON APIs. I ended up writing my own literate JSON spec tool that looked like JSON but was in fact Python:
{"name": str, "age": int, "groups": [str]}
The template has the same 'shape' as the expected JSON, making it very easy for humans to grok.
We put all these specs into a file that acted both as documentation and as the actual Python code we used as templates to validate the real JSON. The doc was always accurate ;)
It turned into a full-blown dynamic type checking thing for Python, but it's still most useful for checking JSON APIs at runtime: https://pypi.python.org/pypi/obiwan/1.0.8 https://pypi.python.org/pypi/obiwan/1.0.8
If you validate the JSON with an obiwan template, you can avoid having to type-check it as you parse it.
Obiwan syntax would be easy to use in other languages, but we never needed to try.
- tracker1 10y agoI often do something similar when documenting a structure as a first pass.. { "name": String, // [required] "age": Number, //int "groups": [String], // groupId (UUID) ... } The structure represents the actual object, and comments allow for additional context/details... it's worked pretty well for documenting APIs that are under development, or intention when working with other devs.
- willvarfar 10y agoYes and with obiwan you can pass that structure to data = json.loads(tainted, template=your_spec) And that will throw an exception if the JSON didn't match the template. From then on its just to safely use the JSON you just loaded, knowing it is well formed and matches the expected shape... :)
- GauntletWizard 10y agoAt that point, you're inches from specifying protobufs or thrift, and the advantages in structured object parsing and tooling that exists from using one of those ecosystems is not to be ignored.
- willvarfar 10y agoJSON is widely used for interchange. Often JSON is a requirement, not a choice.
- tracker1 10y agoIt's worth noting that depending on the language, JSON parsing is faster than binary implementations. Also worth noting that you can do JSON + gzip if there are larger records to be transferred regularly.