#!/usr/bin/env ruby # # Eric Radman 2019 # # Print JSON in a line-oriented format using PostgreSQL JSON operator syntax require 'json' def usage warn 'usage: flattenjs < input.json' exit 1 end color = $stdout.isatty usage if ARGV.pop usage if $stdin.isatty json_in = '' while (line = $stdin.gets) json_in << line end exit if json_in.length <= 1 h = JSON.parse(json_in) # Based on https://stackoverflow.com/a/10715242/1809872 module Enumerable def flatten_with_path(parent_prefix = nil) res = {} each_with_index do |elem, i| if elem.is_a?(Array) k, v = elem else k = i v = elem end key = parent_prefix ? "#{parent_prefix},#{k}" : k if v.is_a? Enumerable # recursive call to flatten child elements res.merge!(v.flatten_with_path(key)) else res[key] = v end end res end end h.flatten_with_path.each do |path, value| if color puts "{#{path}} \e[37m#{value}\e[39m" else puts "{#{path}} #{value}" end end