我正在开发Ruby on Rails。我在我的数据库中有这样的JSON对象:
{"data":[
{"name":"A", "available":"1"},
{"name":"B", "available":"0"}
]}
我想通过添加另一条记录来更新它,它应该如下所示:
{"data":[
{"name":"A", "available":"1"},
{"name":"B", "available":"0"},
{"name":"C","available":"1"}
]}
我该怎么做?
答案 0 :(得分:6)
你可以试试这个
json = { "data" => [
{"name" => "A", "available" => "1"},
{"name" => "B", "available" => "0"}
]}
json["data"].push({"name" => "C", "available" => "1"})
答案 1 :(得分:0)
如果您使用的是ActiveRecord Serialize(或者Rails 5属性api),则该值将已转换为哈希值。
class Model
serialize :some_field, JSON
end
record = Model.find(id)
record.some_field ==>
{"data":[
{"name":"A", "available":"1"},
{"name":"B", "available":"0"}
]}
record.some_field["data"] << {"name" => "C", "available" => "1"}
record.save