Rails - 如何删除散列中的最后一个逗号
Rails - How to remove the last comma in a hash
我各有一个 :
{
"type": "FeatureCollection",
"features": [
<% @pois.each do |poi| %>
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [<%= poi.longitude %>, <%= poi.latitude %> ]
},
<% end %>
]
}
我想删除最后一次迭代的最后一个逗号。我该怎么办?
这不是 json,而是 Geojson。
我想要这样的东西:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [2.484957, 44.6044089 ]
},
"properties": {}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [2.3749903, 44.5656783 ]
},
"properties": {}
}
]
}
没关系,我只想删除最后一个逗号;)
我假设您正在尝试 create/edit 某种 JSON 对象。
您不应该 以这种方式处理JSON 对象。
而是使用 ActiveModel::Serializers
user = User.find(1)
user.as_json
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
# "created_at" => "2006/08/01", "awesome" => true}
ActiveRecord::Base.include_root_in_json = true
user.as_json
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
# "created_at" => "2006/08/01", "awesome" => true } }
由于您可能对将一个数组转换为另一个数组感兴趣,因此可以使用 map
而不是 each
,即
{
"type": "FeatureCollection",
"features":
<% @pois.map do |poi| %>
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [<%= poi.longitude %>, <%= poi.latitude %> ]
}
}
<% end %>
}
我各有一个 :
{
"type": "FeatureCollection",
"features": [
<% @pois.each do |poi| %>
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [<%= poi.longitude %>, <%= poi.latitude %> ]
},
<% end %>
]
}
我想删除最后一次迭代的最后一个逗号。我该怎么办?
这不是 json,而是 Geojson。
我想要这样的东西:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [2.484957, 44.6044089 ]
},
"properties": {}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [2.3749903, 44.5656783 ]
},
"properties": {}
}
]
}
没关系,我只想删除最后一个逗号;)
我假设您正在尝试 create/edit 某种 JSON 对象。
您不应该 以这种方式处理JSON 对象。 而是使用 ActiveModel::Serializers
user = User.find(1)
user.as_json
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
# "created_at" => "2006/08/01", "awesome" => true}
ActiveRecord::Base.include_root_in_json = true
user.as_json
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
# "created_at" => "2006/08/01", "awesome" => true } }
由于您可能对将一个数组转换为另一个数组感兴趣,因此可以使用 map
而不是 each
,即
{
"type": "FeatureCollection",
"features":
<% @pois.map do |poi| %>
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [<%= poi.longitude %>, <%= poi.latitude %> ]
}
}
<% end %>
}