Ruby on Rails JSON.parse (object.to_json) does not return the original object

It seems like with such an object:

#<Course id: 1, name: "Targeting Triple Negative Breast Cancer", description: nil, disclosure: nil, created_at: "2010-11-11 14:43:31", updated_at: "2010-11-11 14:43:31", picture: nil, course_reference_id: nil, authors: "Lisa A. Carey, M.D.", volumn_number: nil, publication_date: nil, expiration_date: nil, credits: 1, featured: false>

I should be able to do it JSON.parse(course.to_json), but when I try to do this, instead of returning the original object, I get the equivalent of Course.new (an object with nil attributes).

When I do course.to_json, I get:

"{\"attributes\":{\"name\":\"Targeting Triple Negative Breast Cancer\",\"expiration_date\":null,\"created_at\":\"2010-11-11 14:43:31\",\"featured\":\"0\",\"publication_date\":null,\"updated_at\":\"2010-11-11 14:43:31\",\"id\":\"1\",\"disclosure\":null,\"volumn_number\":null,\"credits\":\"1\",\"authors\":\"Lisa A. Carey, M.D.\",\"course_reference_id\":null,\"description\":null,\"picture\":null},\"json_class\":\"Course\",\"attributes_cache\":{}}"

But when I do JSON.parse(course.to_json), I get:

#<Course id: nil, name: nil, description: nil, disclosure: nil, created_at: nil, updated_at: nil, picture: nil, course_reference_id: nil, authors: nil, volumn_number: nil, publication_date: nil, expiration_date: nil, credits: nil, featured: false>

I use Rails 2.3.5, and get the same result with other objects.

+3
source share
1 answer

To serialize / deserialize the use of the object #to_jsonand #from_json. Do not try to parse the JSON string yourself.

json = Course.new(...).to_json
Course.new.from_json(json)

, JSON.parse. ActiveSupport::JSON.

+3

Source: https://habr.com/ru/post/1775015/


All Articles