Hacker News new | ask | show | jobs
by MassiveBonk51 1023 days ago
Why does it have to be bash+python? I'm finding myself using node.js scripts glued together by bash ones these days unless I'm working on a lot of data. Doing that means you can work with json natively.
2 comments

`json.loads` in Python exists, and Python does the intuitive thing when you do `{"a": 1} == {"a": 1}`, at least for most purposes (you want the other option? `is` is right there!). Stuff like argparse is not the easiest thing to use but it's in the standard library and relatively easy to use as well.

Not going to outright say that node.js scripts are the worst thing ever (they're not), but out-of-the-box Python is totally underrated (except on MacOS where `urllib` fails with some opaque errors untill you run some random script to deal with certs)

I haven't had a great experience dealing with JSON in Python, but maybe I'm doing it wrong. What would be the Python equivalent of this JS code?

    JSON.parse(<data>).foo?.[0]?.bar
Basically just return the `bar` field of the the first element of `foo`, or None/undefined if it doesn't exist.
Assuming <data> will be a key-value-object aka dict, it would be something like this:

    import json
    data = json.loads('<data>')
    bar = None
    if foo:=data.get('foo'):
        bar = foo[0].bar    
    print(bar)
    
If you can't be sure to get a dict, another type-check would be necessary. If you read from a file or file-like-object (like sys.stdin), json.load should be used.
I love nodejs, it's my go-to language for server side stuff.

Even with that bias though, I have to admit that it's awful for typical command line script stuff.

Dealing with async and streams and stuff for parsing csv files is miserable (I just wrote some stuff to parse and process hundreds of gigs of files in node, and it wasn't fun).

Python is the right tool for that job IMHO.

Also, weirdly, maybe golang? I just came across this [1] and it has one of my eyebrows cocked.

[1] https://bitfieldconsulting.com/golang/scripting

Ruby is the clear answer here. The fact that more people don't use it for this purpose (its intended purpose!) is a travesty.
Any not-designed-specifically-for-shell language will suck for shell, more or less. Ruby, python, node, whatever, they all have the same problem - you write stuff too much and care about stuff you shouldn't care while in shell.
You're probably right. I just wish there was an easier way to handle json on the command line that didn't turn into its own dsl. The golang scripting seems interesting, might be what motivates me to learn the language.