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

rog*_*one 30 ruby json ruby-on-rails

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

[{"content":"1D","createdTime":"09-06-2011 00:59"},{"content":"2D","createdtime":"09-06-2011 08:00"}]
Run Code Online (Sandbox Code Playgroud)

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

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

Jer*_* B. 61

您可以使用json库json

然后你可以这样做:

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

在回复您的评论时,您可以执行此操作,只要您的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
Run Code Online (Sandbox Code Playgroud)


Mar*_*rio 37

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

  • 这应该是明确的答案,没有额外的依赖 (4认同)