Rails:JSON格式错误

时间:2013-07-25 05:37:20

标签: ruby-on-rails json

我需要连接两个JSON对象并在JSON.erb文件中显示结果。现在,使用以下代码,我得到了许多无关的反斜杠。我该怎样摆脱它们?

我期待这样的事情:

{ 
    "success":true, 
    "info":"ok", 
    "data":
        { "steps":
            [
  {
    "id": 243,
    "last": false,
    "name": "Project Overview",
    "position": 0,
    "published_on_formatted": "07/18/2013 14:15:00",
    "images": [
      {...

我得到了这个:

{ 
    "success":true, 
    "info":"ok", 
    "data":
        { "steps":
            [
  "{\"id\":721,\"last\":false,\"name\":\"Project Overview\",\"position\":0,\"images\":...

我的index.html.erb文件:

{ 
    "success":true, 
    "info":"ok", 
    "data":
        { "steps":
            <% first_step = @project.first_step.to_json(only: [:name, :id, :last, :position], include: {images: {only: [:image_path, :position, :id] } } ).html_safe%>
            <% other_steps = @project.non_overview_steps.to_json(only: [:name, :id, :last, :position], :methods=> :published_on_formatted, include: {images: {only: [:image_path, :position, :id] } } ).html_safe %>
            <% all_steps = first_step + other_steps %>
            <%= JSON.pretty_generate([all_steps]).html_safe %> 
    } 
}

2 个答案:

答案 0 :(得分:0)

这就是我修复json.erb文件的方法:

{ 
    "success":true, 
    "info":"ok", 
    "data":
        { "steps":
            <% first_step = @project.first_step.as_json(only: [:name, :id, :last, :position], include: {images: {only: [:image_path, :position, :id] } } )%>
            <% other_steps = @project.non_overview_steps.as_json(only: [:name, :id, :last, :position], :methods=> :published_on_formatted, include: {images: {only: [:image_path, :position, :id] } } ) %>
            <% all_steps = other_steps.unshift(first_step) %>
            <%= JSON.pretty_generate(all_steps).html_safe %>
    } 
}

答案 1 :(得分:0)

使用<%=raw ... %>以避免转义。

我会在多维哈希中构建所有内容,并最终在其上调用to_json