Last active
August 19, 2018 00:26
-
-
Save kemchenj/874315f8f08b6cee27d58d796fb24f80 to your computer and use it in GitHub Desktop.
json2mson
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
require 'json' | |
def base_type?(element) | |
element.is_a?(Numeric) || element.is_a?(String) || element.is_a?(TrueClass) || element.is_a?(FalseClass) | |
end | |
def base_type_array?(arr) | |
base_type?(arr.first) | |
end | |
def value_type(value) | |
if value.is_a? String | |
'string' | |
elsif value.is_a? Numeric | |
'number' | |
elsif value.is_a?(TrueClass) || value.is_a?(FalseClass) | |
'boolean' | |
elsif value.is_a? Array | |
'array' | |
elsif value.is_a? Hash | |
'object' | |
elsif value.nil? | |
'nullable' | |
else | |
'unknown' | |
end | |
end | |
class KO | |
attr_accessor :key_paths | |
attr_accessor :object | |
def initialize(key_paths, obejct) | |
@key_paths = key_paths | |
@object = obejct | |
end | |
def current_key_paths_str | |
@key_paths.join('.') | |
end | |
end | |
input_filename = $*[0] | |
file_content = `cat #{input_filename}` | |
root_json_object = JSON.parse(file_content) | |
object_queue = Array.new | |
object_queue.push(KO.new(["_Root_"], root_json_object)) | |
while ko = object_queue.delete_at(0) do | |
key_paths = ko.key_paths.clone | |
puts "### `#{ko.current_key_paths_str}`\n\n" | |
ko.object.each { |key, value| | |
key_paths.push key.capitalize | |
if value.is_a? Hash | |
object_queue.push(KO.new(key_paths, object)) | |
puts "- `#{key}`: `#{key_paths.join('.')}`" | |
elsif value.is_a?(Array) && !value.empty? && base_type_array?(value) | |
puts "- `#{key}` #{value.map { |v| "`#{v}`" }.join(' ')} (array)" | |
elsif value.is_a?(Array) && !value.empty? | |
element_key_paths = Array.new | |
value.each.with_index { |e, i| | |
new_key_paths = key_paths.clone | |
new_key_paths.push i.to_s | |
new_key_paths_str = new_key_paths.join('.') | |
element_key_paths.push new_key_paths_str | |
object_queue.push(KO.new(new_key_paths, e)) | |
} | |
puts "- `#{key}` (array[#{element_key_paths.join(', ')}])" | |
elsif base_type?(value) | |
puts "- `#{key}`: `#{value}` (#{value_type(value)})" | |
end | |
key_paths.pop | |
} | |
puts "\n" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment