【问题标题】:parsing json string in ruby在ruby中解析json字符串
【发布时间】:2014-09-23 03:46:56
【问题描述】:

我正在尝试通过 ajax 调用解析来自我的控制器的 json 字符串。正在解析的 json 字符串位于 js.erb 文件中。我将代码设置为类似于此堆栈溢出建议:Parsing a JSON string in Ruby。我添加了 gem,但是我不得不将 放在代码的 ruby​​ 部分周围,而不是简单地添加代码,因为它是 js.erb 文件而不是 .rb 文件

我的完整 js.erb 文件如下所示:

    <% require 'json' %>

$(document).ready(function()
{


 $('#collaboration_user_name').on('keyup', function() { 

  text = $(this).val();
  // alert(text);

  $.ajax({ url: "/collaborations?collaboration="+text, 
    beforeSend: function( xhr ) { 
      xhr.overrideMimeType( "text/plain; charset=x-user-defined" ); 
    } 
  }).done(function( data ) {
    console.log( "data:", data ); 
    users = JSON.parse(data);

    $("#user_data ul li").remove();
    $.each( users, function( index, value ) {
      $("#user_data ul").append("<li role='presentation'>"+"<a role='menuitem' tabindex='-1' href='#'>"+users[index].name+ ", " +users[index].email+"</a>"+"</li>"); 
    });
  <% @user = "data" %>;
    $("#user_data").append(<%= JSON.parse @user %>);
});

 });
});

要注意的代码是

 <% require 'json' %>

在顶部和

 <% @user = "data" %>;
 $("#user_data").append(<%= JSON.parse @user %>);

在页面底部。当我添加这些行时,我得到一个错误。

JSON::ParserError in Wikis#edit
Showing /Users/warren/code/knowledgebank/app/views/layouts/application.html.erb where line #7         raised:

757: unexpected token at 'data'
  (in /Users/warren/code/knowledgebank/app/assets/javascripts/collaborations.js.erb)
   Extracted source (around line #7):

4<title>Knowledgebank</title>
5<%= stylesheet_link_tag "application", media: "all" %>
6
7<%= javascript_include_tag 'application'%>
8<%= csrf_meta_tags %>
9</head>
10<body>

如何使 JSON.parse 使 ruby​​ 工作?在javascript中它工作正常。

【问题讨论】:

  • "data" 无效JSON。

标签: ruby-on-rails ruby ajax json


【解决方案1】:

你现在做的是:

require 'json'

JSON.parse('data') # which throws unexpected token at 'data' because JSON can't parse the string 'data'

如果您的目标只是将解析后的 json 附加到 dom 元素,那么我认为不需要 JSON 并在 ruby​​ 中执行它?

这个javascript应该没问题(检查这个SO answer):

.done(function(data) {
  $("#user_data").append(JSON.parse(data));
}

【讨论】:

  • 我在 ruby​​ 中需要它,因为我想添加 ruby​​ 的 link_to 方法,以便在单击时将从 json 对象获取的信息传递回控制器。
猜你喜欢
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 2018-09-18
相关资源
最近更新 更多