在HTML中显示格式化的JSON,而无需JavaScript(Ruby、Sinatra)。

问题描述 投票:0回答:2

我正在用Ruby + Sinatra构建一个实践性的Web API,我希望我的响应能以格式化的JSON(GeoJSON)显示在一个ERB模板中。到目前为止,我已经能够处理请求并正确格式化响应。

然而,我无法找到一种方法来将端点中的内容显示为JSON字符串,它显示为一个常规的字符串(对于JSON来说很难读取)。有没有什么方法可以在Ruby+Sinatra中不使用JavaScript来实现呢?

这是我目前在这两个文件中的情况。

# 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 %>
json ruby sinatra geojson
2个回答
0
投票

尝试 <%= @activities.to_json.html_safe %>


0
投票

你可以通过使用以下方法让JSON字符串看起来更漂亮 JSON.pretty_generate() 方法。

# 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

并在你的erb文件中。不是简单的显示,而是在你的erb文件中添加 <pre> 标签。

<!--cities.erb-->

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

引用

© www.soinside.com 2019 - 2024. All rights reserved.