将Rails中的JSON字符串转换为JSON数组? [英] Convert JSON String to JSON Array in rails?

查看:231
本文介绍了将Rails中的JSON字符串转换为JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JSON string in rails as shown below:

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

是具有内容内容和创建时间的类内容的对象.

which are the objects of a class content with attributes content and created time.

我想将此JSON字符串转换为其各自的JSON对象数组,以便我可以运行循环并在rails中将JSON解码为其对象.我该如何实现?

I would like to convert this JSON string to its respective JSON object array so that I can run a loop and decode the JSON to its objects in rails. How can I achieve this?

推荐答案

您可以使用json库 json

You can use the json library json

您可以执行以下操作:

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

只要您的JSON适合您的模型,就可以对您的评论做出回应

In response to your comment, you can do this, as long as your JSON fits your model

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

这篇关于将Rails中的JSON字符串转换为JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆