0

我需要连接两个 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 %> 
    } 
}
4

2 回答 2

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 %>
    } 
}
于 2013-07-25T05:48:53.250 回答
0

用于<%=raw ... %>避免逃逸。

我会在多维散列中构建所有内容并to_json最终调用它。

于 2013-07-25T05:49:06.370 回答