在 Rails 中,这是我当前生成的一个 api 响应,作为来自 /charts_json/south_carolina.json 的响应(例如)
[{"d_s":0,"name":"summerville"},{"d_s":1,"name":"hilton head island"},{"d_s":2,"name":"north myrtle beach"},{"d_s":1,"name":"spartanburg"},{"d_s":12,"name":"greenville, sc"},{"d_s":0,"name":"aiken"},{"d_s":6,"name":"columbia"},{"d_s":4,"name":"myrtle beach"},{"d_s":1,"name":"simpsonville"},{"d_s":1,"name":"lancaster, sc"},{"d_s":0,"name":"north augusta"},{"d_s":0,"name":"sumter"},{"d_s":0,"name":"rock hill"},{"d_s":1,"name":"beaufort, sc"},{"d_s":1,"name":"mount pleasant"},{"d_s":21,"name":"charleston"},{"d_s":1,"name":"clemson"},{"d_s":1,"name":"anderson, sc"}]
现在我需要做的是像这样将上面的内容呈现为 json 文档
[['0', 'summerville'], ['1', 'hilton head island'], ...etc... ]
为了 SO 社区的利益和读者的澄清,如果我处理最后一件事情,我将包括我将用来完成这项工作的所有代码
除了我的charts_controller,我还生成了一个charts_json_controller 来响应json 请求——该控制器中的控制器方法的一个示例(这有点笨拙,但现在只要我能获得功能就可以了)
def south_carolina
@locations = Location.find(1687).descendants #used acts_as_tree gem
respond_to do |format|
format.json { render json: @location.as_json(only: [:d_s, :name])}
end
在视图中(横截面)
function drawMarkersMap() {
var data = google.visualization.arrayToDataTable([
['Startups', 'Location'],
$.ajax({url: '/charts_json/south_carolina', dataType: 'json'})
]);