Skip to content

Instantly share code, notes, and snippets.

@horttanainen
Last active April 14, 2019 12:20
Show Gist options
  • Save horttanainen/92dcf49c34d33f367ab90a72e7ac8da9 to your computer and use it in GitHub Desktop.
Save horttanainen/92dcf49c34d33f367ab90a72e7ac8da9 to your computer and use it in GitHub Desktop.
Prettify and transform json from command line
#!/usr/bin/env bash
JS='
var toEval = process.argv[1];
process.stdin.resume();
process.stdin.setEncoding("utf8");
var json = "";
process.stdin.on("data", function(buf) {
json += buf;
});
process.stdin.on("end", function() {
const obj = JSON.parse(json);
const modifiedJObj = eval(toEval);
console.log(JSON.stringify(modifiedJObj, null, 2));
});
'
node -e "$JS" -- "$1"
@horttanainen
Copy link
Author

horttanainen commented Apr 13, 2019

Add the snippet in your .bashrc

alias pjsone='sh ~/.scripts/pretty-print-json-extended.sh'

Try it out:

echo '{"a": { "b": [1, 2, 3]}}' | pjsone "obj.a.b[1]"
echo '{"a": { "b": [1, 2, 3]}}' | pjsone "obj.a.b.map(item => item * 2)"

@horttanainen
Copy link
Author

horttanainen commented Apr 13, 2019

You can use other packages as well (if you install them alongside the script):

echo '{"a": { "b": [1, 2, 3]}}' | pjsone "var R = require('ramda'); R.zip(obj.a.b, obj.a.b)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment