from_json
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3 (0)
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
Instance method
Please note that this is an instance method, not a class method (which seemed more logical for me and took me a while to see what’s wrong). So, you call it like this:
User.new.from_json '{"id": 1, "name": "DHH"}' # RIGHT!
not like this:
User.from_json '{"id": 1, "name": "DHH"}' # WRONG!
Be careful about ActiveRecord::Base.include_root_in_json
If you have set ActiveRecord::Base.include_root_in_json = true, then when you do .to_json on an object, the output will begin with the class name rather than just a hash of attributes.
from the rails docs
konata = User.find(1) ActiveRecord::Base.include_root_in_json = true konata.to_json => { "user": {"id": 1, "name": "Konata Izumi", "age": 16, "created_at": "2006/08/01", "awesome": true} }
if you try to pass this output as the argument to from_json, things will blow up.
User.new.from_json(konata.to_json[“user”]) will just pass in the attribute hash and will work.
Also, note that if you’ve use attr_accessible to limit mass assignment, you’ll have problems if you try pass in attributes that are not allowed to be mass assigned.