Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In the common case where you trust your input entirely you can just interpret your string as JavaScript. Then you don't even need to use quotes for the key names.

    $ alias fooson="node --eval \"console.log(JSON.stringify(eval('(' + process.argv[1] + ')')))\""
    $ fooson "{time: $(date +%s), dir: '$HOME'}"
    {"time":1457195712,"dir":"/Users/jpm"}
It may be a bit nicer to place that JavaScript in your path as a node script instead of using an alias.

    #!/usr/bin/env node
    console.log(JSON.stringify(eval('(' + process.argv[2] + ')')))
Since fooson's argument is being interpreted as JavaScript, you can access your environment through process.env. But you could make a slightly easier syntax in various ways. Like with this script:

    #!/usr/bin/env node
    for(const [k, v] of Object.entries(process.env)) {
        if (!global.hasOwnProperty(k)) {
            global[k] = v;
        }
    }
    console.log(JSON.stringify(eval('(' + process.argv[2] + ')')))
Now environmental variables can be access as if they were JS variables. This can let you handle strings with annoying quoting.

    $ export BAR="\"'''\"\""
    $ fooson '{bar: BAR}'
    {"bar": "\"'''\"\""}
If you wanted to do this without trusting your input so much, a JSON dialect where you can use single-quoted strings would get you pretty far.

    $ fooson "{'time': $(date +%s), 'dir': '$HOME'}"
    {"time":1457195712,"dir":"/Users/jpm"}
If you taught the utility to expand env variables itself you'd be able to handle strings with mixed quoting as well.

    $ export BAR="\"'''\"\""
    $ fooson '{"bar": "$BAR"}'
    {"bar": "\"'''\"\""}
You'd only need small modifications to a JSON parser to make this work.


Ended up sniping myself . Made a fairly complete version of what I was imagining: https://github.com/itsjohncs/construct-json#readme




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: