Convert JSON String to JSON Array in rails?

前端 未结 3 842
谎友^
谎友^ 2021-02-01 14:58

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         


        
3条回答
  •  梦毁少年i
    2021-02-01 15:54

    You can use the json library json

    You can then do:

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

    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
    

提交回复
热议问题