在javascript中将包含HTML的哈希树解析为JSON

时间:2014-11-13 10:11:30

标签: javascript jquery ruby-on-rails json erb

我一直试图找出从rails后端解析一个hashtree作为javascript中的JSON。在stackoverflow和其他方面尝试了几种解决方案,包括:

我想解析的对象:

{  
   "name"=>"map",
   "children"=>[  
      {  
         "name"=>"servicegroup1",
         "children"=>[  
            {  
               "name"=>"service1",
               "size"=>200,
               "id"=>10,
               "tooltip"=>"      <h3 id=\"status_tooltip_heading\">Service status<\/h3>\n      \n      <table id=\"status_tooltip_grid\">      \n        <tbody>\n          <tr>\n            <td>Status:<\/td>\n            <td>Unknown (an eternity ago)<\/td>          \n          <\/tr>\n          <tr>\n            <td>HTTP code:<\/td>\n            <td>\"N/A\"<\/td>          \n          <\/tr>                \n          <tr>\n            <td>Response time:<\/td>\n            <td>\"N/A\"<\/td>          \n          <\/tr>\n            <td>Event message:<\/td>\n            <td>Not pinged since eternity<\/td>          \n          <\/tr>\n        <\/tbody>\n      <\/table>\n"
            },
            {  
               "name"=>"service2",
               "size"=>200,
               "id"=>11,
               "tooltip"=>"      <h3 id=\"status_tooltip_heading\">Service status<\/h3>\n      \n      <table id=\"status_tooltip_grid\">      \n        <tbody>\n          <tr>\n            <td>Status:<\/td>\n            <td>Unknown (an eternity ago)<\/td>          \n          <\/tr>\n          <tr>\n            <td>HTTP code:<\/td>\n            <td>\"N/A\"<\/td>          \n          <\/tr>                \n          <tr>\n            <td>Response time:<\/td>\n            <td>\"N/A\"<\/td>          \n          <\/tr>\n            <td>Event message:<\/td>\n            <td>Not pinged since eternity<\/td>          \n          <\/tr>\n        <\/tbody>\n      <\/table>\n"
            },
            ...
         ]
      },
      ...
   ]
}

以下是我目前正试图在javascript中将其解析为JSON,并尝试了上述链接中的技术。

<script>jsonObj = JSON.parse('<%==(raw @map.to_s).gsub("=>",":").gsub("</","<\\/") %>')</script>

现在已经坚持了几个小时。我真的很感激你能给我的任何见解。 此外,rails版本是4.1.2

1 个答案:

答案 0 :(得分:1)

这足以使用:

<script>jsonObj = <%=raw ( @map.to_json) %></script>