Pretty Print JSON From The Command Line

JSON can come in all shapes and sizes, and sometimes you want to see it in a structured format that’s easier on the eyes. This is called pretty printing. But how do you accomplish that, especially if you have a really large JSON file? While there are some converter tools online to show json files in a pretty format, they can get very slow and even freeze if your file is too large. Let’s do it locally.

Requirements: Have Python installed, and a terminal environment.

cat file.json | python -m json.tool > prettyfile.json

And that’s all there is to it! Python comes built in with a JSON encoding/decoding library, and you can use it to your advantage to get nice formatted output. Alternatively, if you are receiving JSON from an API or HTTP request, you can pipe your results from a curl call directly into this tool as well.

Hope this helps!

Advertisements

Linux/Programming Snippets – Wave 2

Here’s some more useful things I’ve found myself using lately. Yeah, they’re trivial, but I’m putting them here so they will be easy to refer back to.

how to do simple arithmetic in a bash script
$((1+1)) does 1+1
$(($i+2)) does the variable i + 2

how to alias something in bash
alias youralias=’the command to run’
example: alias ls=’ls -l’

to print the nth line of a file
cat yourfile | sed -n 2p

basic git commands

  • git add yourfile – adds yourfile to the repository
  • git commit – add a commit message, commits the file changes for all “added” files
  • git push origin master – pushes the changes to github
  • git pull – pulls down the most recent changes into your local repository

Useful Linux/Programming Snippets – Wave 1

I’ve been keeping a list of things I’ve had to look up for school or work, programming wise, and I thought it might be helpful to list them here. It’s more of a reference than anything, and I know it helps me to look back on it if I forget something little, so maybe someone else will find it useful too.

to execute a premade .sql file
mysql -p -D databasename < file.sql

find/replace in Emacs (discriminately, that is: it will ask you at each instance if you want to replace)
M-x query-replace <ENTER>
oldstring <ENTER>
newstring <ENTER>

  •     space – replace
  •     n – skip
  •     enter – quit

cat a bunch of files together into one
cat file1 file2 > allfiles
or
cat file* > allfiles

to get unix time in bash
date +%s

to get unix time in mySQL
select UNIX_TIMESTAMP(now());

rename a table in mySQL
RENAME TABLE oldname TO newname;

I’ll probably add more as I find them.