Hacker News new | ask | show | jobs
by name_for_now 3381 days ago
Hmm, seems like the author either does not know about JSON.mapping [0] or just chose not to use it. Honestly, the corresponding macro for YAML is the main reason I use Crystal for CLI apps since it comes with the stdlib. YAML is easy enough to write quickly that I don't have to do too much with option parsing. Plus you can just use your editor rather than the shell.

[0] https://crystal-lang.org/api/master/JSON.html#mapping%28prop...

1 comments

I do use it in this project, but most definitely in the wrong way. I had a little trouble seeing how I could use it for getting at nested values of varying types and still have some sane error handling.

This post is very much about my first pass at this and my first experience with Crystal. Cleaning up the JSON parsing is the next item on my list when I have time.

Here's a quick gist that does what I think you want, modulo any specific error handling. https://gist.github.com/usernamefornow/14f972df9429146b46846...

edit: note that the cleanest way would probably to write your own converter so you could avoid the union type, but I didn't want to put that in and have to write a comment about it.

Makes sense, thanks. For some reason, I was set on parsing the "env" values into instances of the same class, regardless of what type they were in JSON, but it's not really necessary. I'll also look into writing custom converters, because I'll likely need that in the future.
You can pass union types to the macro, so that should handle your "varying types" problem. In terms of nesting, I just create another struct with its own JSON.mapping and use that as the type for the field.