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

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

它们是类内容的对象,具有内容属性和创建时间.

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

然后你可以做:

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

作为对您的 comments 的回应,您可以这样做,只要您的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

Json相关问答推荐

jq不会为空输入返回非零

在T—SQL中将STR_AGG与JSON_ARRAY结合起来

如何使用Laravel在MariaDB JSON kolumn中使用unicode字符

419(未知状态)使用laravel处理PUT请求

使用 Redis 作为键值存储

如何在 jq 中按 IP 地址排序?

使用 map_values Select 包含空格的字符串未按预期工作

我需要在 mongodb compass 中检索索引(编号 1)信息

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

在 postgresql 中将行转换为 json 对象

Json.NET SerializeObject 转义值以防止 XSS

如何使用 jackson 反序列化为 Kotlin 集合

在 Apache Spark 中读取多行 JSON

编写 JSON 日志(log)文件的格式?

如何在java中比较来自JsonObject的空值

jQuery.getJSON 和 jQuery.parseJSON 返回 [object Object]?

区分字符串和列表的 Pythonic 方式是什么?

将多个值存储在json中的单个键中

Laravel 5 控制器将 JSON 整数作为字符串发送

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?