Rails:从JSON数组重建ActiveRecord对象

时间:2021-11-27 12:21:56

I have a JSON array with ActiveRecord objects. These objects can be reconstructed using the from_json method, which every AR object has. However with from_json it's only possible to reconstruct one single object.

我有一个带有ActiveRecord对象的JSON数组。可以使用每个AR对象具有的from_json方法重建这些对象。但是使用from_json,它只能重建一个单个对象。

To process an array, I could of course just extract substrings from the JSON array and create every object from it's own substring in a loop or so. However I'm wondering if there is a better way to do this, without string manipulation involved.

为了处理数组,我当然可以从JSON数组中提取子字符串,并在循环中从它自己的子字符串中创建每个对象。但是我想知道是否有更好的方法来执行此操作,而不涉及字符串操作。

1 个解决方案

#1


6  

I would do

我会做

sudo gem install json

After that just

在那之后

require "json"

and do

JSON.load(array_of_ar_json_representation)

or

JSON.parse(array_of_ar_json_representation)

what fits better for you.

什么更适合你。

Both of these methods return Ruby data structure that corresponds to the json structure. So, if you have a json array of obejcts, after JSON.load or JSON.parse you'll get Ruby array of hashes. You should't have any problems to manipulate this kind of structure.

这两种方法都返回对应于json结构的Ruby数据结构。所以,如果你有一个json数组的obejcts,在JSON.load或JSON.parse之后你会得到Ruby数组的哈希值。操纵这种结构你不应该有任何问题。

#1


6  

I would do

我会做

sudo gem install json

After that just

在那之后

require "json"

and do

JSON.load(array_of_ar_json_representation)

or

JSON.parse(array_of_ar_json_representation)

what fits better for you.

什么更适合你。

Both of these methods return Ruby data structure that corresponds to the json structure. So, if you have a json array of obejcts, after JSON.load or JSON.parse you'll get Ruby array of hashes. You should't have any problems to manipulate this kind of structure.

这两种方法都返回对应于json结构的Ruby数据结构。所以,如果你有一个json数组的obejcts,在JSON.load或JSON.parse之后你会得到Ruby数组的哈希值。操纵这种结构你不应该有任何问题。