在rails中将JSON字符串转换为JSON数组?

我在rails中有一个JSON字符串,如下所示:

[{"content":"1D","createdTime":"09-06-2011 00:59"},{"content":"2D","createdtime":"09-06-2011 08:00"}] 

哪些是具有属性内容和创建时间的类内容的对象。

我想将此JSON字符串转换为其各自的JSON对象数组,以便我可以运行循环并将JSON解码为其在rails中的对象。 我怎样才能做到这一点?

您可以使用json库json

然后你可以这样做:

 jsonArray = [{"content":"1D","createdTime":"09-06-2011 00:59"}, {"content":"2D","createdtime":"09-06-2011 08:00"}] objArray = JSON.parse(jsonArray) 

在回复您的评论时,您可以执行此操作,只要您的JSON适合您的模型即可

 objArray.each do |object| # This is a hash object so now create a new one. newMyObject = MyObject.new(object) newMyObject.save # You can do validation or any other processing around here. end 

ActiveSupport::JSON.decode(string)将为您解码为服务器端的美味消耗品对象。

如果JavaScript代码是内部的,那么您可以这样做:

  

除此以外:

创建隐藏的textarea并将@ hives.html_safe设置为其值,现在您可以在JavaScript中将其作为元素的值获取,如下所示:

在html.erb文件中

 <%= text_area_tag :hives_yearly_temp, @hives.html_safe, { style: "display: none;"} %> 

在js文件中

 var hives = JSON.parse( $('#hives_yearly_temp').val() ); 

运行循环

 for(key in hives) { alert( hives[key] ); }