Rails - 如何删除哈希中的最后一个逗号

时间:2018-04-29 16:22:04

标签: ruby-on-rails geojson

我有一个:

{
  "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": {}
    }
  ]
}

一切都没问题,我只想删除最后一个逗号;)

2 个答案:

答案 0 :(得分:0)

我认为您正在尝试创建/编辑某种JSON对象。

不应该以这种方式处理JSON对象。 而是使用ActiveModel :: Serializers

来自ActiveModel::Serializers

function showUser(str) {
  if (str === "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
  } else { 
  if (window.XMLHttpRequest) {
  // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    } 
    xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("txtHint").innerHTML = this.responseText;
      }
    };
  xmlhttp.open("GET","../php/countrysideupdateviews.php?q="+str,true);
  xmlhttp.send();
  event.preventDefault();
  }
}

答案 1 :(得分:0)

由于您可能对将数组转换为另一个数组感兴趣,因此可以使用map代替each,即

{
  "type": "FeatureCollection",
  "features": 
   <% @pois.map do |poi| %>
     {
       "type": "Feature",
       "geometry": {
         "type": "Point",
         "coordinates": [<%= poi.longitude %>, <%= poi.latitude %> ]
       }
     }
   <% end %>
}