I think this recursive function does a good job at converting the JSON file to a pretty html page.
def parse(hash, iteration=0 )
iteration += 1
output = ""
hash.each do |key, value|
if value.is_a?(Hash)
output += "<div class="entry" style="margin-left:#{iteration}em"> <span style="font-size:#{250 - iteration*20}%">#{key}: </span><br>"
output += parse(value,iteration)
output += "</div>"
elsif value.is_a?(Array)
output += "<div class="entry" style="margin-left:#{iteration}em"> <span style="font-size:#{250 - iteration*20}%">#{key}: </span><br>"
value.each do |value|
if value.is_a?(String) then
output += "<div style="margin-left:#{iteration}em">#{value} </div>"
else
output += parse(value,iteration-1)
end
end
output += "</div>"
else
output += "<div class="entry" style="margin-left:#{iteration}em"> <span style="font-weight: bold">#{key}: </span>#{value}</div>"
end
end
return output
end
Here is how it works. You pass it a hash Which you get by converting the JSON file to a hash:
jsonFile = JSON.load(open(params["url"] ))
@output = parse(jsonFile)
And the function checks each value in the hash and does 1 of 3 things:
- If it is an array outputs each array element on a new line
- If it is a string outputs the key and the value on the same line
- If it is another Hash calls the same function
After this all you have to do it output the @output variable to the screen on the view file:
<%= @output.html_safe %>
What the iteration does is keep track of how many times the function has been called so that the output can be indented correctly
I hope this helps anybody else who is trying to do the same thing.
solved How can I convert a JSON file to a html page in Ruby on Rails? [closed]