Skip to content

Instantly share code, notes, and snippets.

@carlzulauf
Created June 23, 2018 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlzulauf/84aa159ee9e0ecb101dce8a6e79fceeb to your computer and use it in GitHub Desktop.
Save carlzulauf/84aa159ee9e0ecb101dce8a6e79fceeb to your computer and use it in GitHub Desktop.
Pretty Print JSON
#!/usr/bin/env ruby
# Pretty print json
#
# Reads JSON from file(s) or from STDIN
#
# Usage:
#
# cat my_json.json | pjson
# pjson my_json.json
# pjson file1.json file2.json
#
require 'json'
jsons = ARGV.map do |file|
begin
File.read(file)
rescue
puts "Cannot read file: #{file}"
end
end
jsons << STDIN.read unless STDIN.tty?
jsons.compact!
jsons.each do |json|
begin
puts JSON.pretty_generate JSON.parse(json)
rescue JSON::ParserError => e
puts "Not valid JSON"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment