Skip to content

Instantly share code, notes, and snippets.

@joaoneto

joaoneto/README.md

Last active May 23, 2016
Embed
What would you like to do?
Improve your curl with pretty formmated json responses

Improve your curl with pretty formmated json responses

requirements node.js

add in your .zshrc

[[ -s $HOME/bin/prettycurl.sh ]] && . $HOME/bin/prettycurl.sh
  • if you don't have, then create a $HOME/bin dir
  • put the pretty-json and prettycurl.sh in $HOME/bin and add execution permission in both of them

execute this command, to apply changes:

source $HOME/.zshrc
#!/usr/bin/env node
var stdin = process.openStdin();
var buffer = '';
var colors = {
black: '\033[30m',
red: '\033[31m',
green: '\033[32m',
yellow: '\033[33m',
blue: '\033[34m',
magenta: '\033[35m',
cyan: '\033[36m',
white: '\033[37m',
reset: '\033[0m'
};
function pretty(obj) {
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
return JSON.stringify(JSON.parse(obj), null, 2)
.replace(jsonLine, function(match, pIndent, pKey, pVal, pEnd) {
var key = colors.white;
var val = colors.cyan;
var str = colors.yellow;
var r = pIndent || '';
if (pKey)
r = r + key + pKey.replace(/[": ]/g, '') + colors.reset + ': ';
if (pVal)
r = r + (pVal[0] == '"' ? str : val) + pVal + colors.reset;
return r + (pEnd || '');
});
}
stdin.setEncoding('utf8');
stdin
.on('data', function (chunk) {
buffer += chunk;
})
.on('end', function () {
if (buffer.slice(0, 5) === 'HTTP/') {
var index = buffer.indexOf('\r\n\r\n');
var sepLen = 4;
if (index == -1) {
index = buffer.indexOf('\n\n');
sepLen = 2;
}
if (index != -1) {
process.stdout.write(buffer.slice(0, index+sepLen));
buffer = buffer.slice(index+sepLen);
}
}
if (buffer[0] === '{' || buffer[0] === '[') {
try {
process.stdout.write(pretty(buffer));
process.stdout.write('\n');
} catch(e) {
process.stdout.write(buffer);
if (buffer[buffer.length - 1] !== '\n') {
process.stdout.write('\n');
}
}
} else {
process.stdout.write(buffer);
if (buffer[buffer.length - 1] !== '\n') {
process.stdout.write('\n');
}
}
});
http () {
curl -H "Content-Type: application/json" -X $* 2>/dev/null | pretty-json
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.