Created
June 23, 2018 01:02
-
-
Save carlzulauf/84aa159ee9e0ecb101dce8a6e79fceeb to your computer and use it in GitHub Desktop.
Pretty Print JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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