-1

I'm building a practice Web API with Ruby + Sinatra and I want my responses to be displayed in a ERB template with formatted JSON (GeoJSON). So far I've been able to process the request and format the response correctly.

However, I can't find a way to display the contents in the endpoint as a JSON string, and it displays as a regular string (difficult to read for JSON). Is there any way to do that in Ruby + Sinatra without using JavaScript?

Here's what I've got so far in both files.

# app.rb

before do
    json = File.open("data/cities.json").read
    data = JSON.parse(json)
    data.each do |item|
        geoarray["features"].append(json_to_geojson(item))
    end
    @geojson = geoarray.to_json
end

...

get('/myendpoint') do
    @activities = @geojson
    erb :cities
end
<!--cities.erb-->

<%= @activities %>
danielsto
  • 134
  • 5
  • 17

2 Answers2

0

try <%= @activities.to_json.html_safe %>

Dev.rb
  • 487
  • 6
  • 14
0

You can make JSON string look prettier by using JSON.pretty_generate() method.

# app.rb
before do
    json = File.open("data/cities.json").read
    data = JSON.parse(json)
    data.each do |item|
        geoarray["features"].append(json_to_geojson(item))
    end

    # use pretty_generate instead of to_json 
    @geojson = JSON.pretty_generate(geoarray)
end

And In your erb file. Instead of simple showing it, add <pre> tag to it.

<!--cities.erb-->

<pre><%= @activities %></pre>

reference

Dylandy
  • 171
  • 1
  • 5