我对rails很新,我所拥有的是一个散列作为json传递给一种格式,现在我需要将它传递给视图才能使用但是我不知道如何迭代哈希到使它在视图中工作,因为我需要在它上面做一些类型的每个循环。它是一个二维哈希dunno,如果这意味着什么或不。
修改
例如
{"status":"successful","service_list":[{"service_name":"mySQL","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"PHP","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"APache","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"Jetty","status":"RUNNING","status_message":"No errors reported","host":"1"}]}
当我以JSON身份执行此操作时,这会呈现正常,但在基于HTML的视图中使用相同的内容进行渲染是我遇到的问题
答案 0 :(得分:1)
您已将Ruby已转换为JSON哈希,这是一种Javascript格式。在Ruby中,您将访问哈希,如下所示:
hash = {"foo": "bar"}
puts hash["foo"] # This returns "bar"
JSON类似于Ruby,可以以相同的方式访问:
var hash = {"foo": "bar"};
alert(hash["foo"]); # This alerts "bar"
如果您想在Javascript中遍历此集合,可以使用for循环:
var data = {"status":"successful","service_list":[{"service_name":"mySQL","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"PHP","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"APache","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"Jetty","status":"RUNNING","status_message":"No errors reported","host":"1"}]};
for(x=0;x<data["service_list"].length;x++) {
alert(data["service_list"][x]["service_name"]); # This returns "mySQL", ...
};
如果您想将此JSON对象转换为Ruby,可以使用JSON字符串作为参数调用“JSON.parse”。