instance method from_json

Ruby on Rails 6.1.7.10

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

from_json(json, include_root = include_root_in_json)

Sets the model attributes from a JSON string. Returns self.

class Person
  include ActiveModel::Serializers::JSON

  attr_accessor :name, :age, :awesome

  def attributes=(hash)
    hash.each do |key, value|
      send("#{key}=", value)
    end
  end

  def attributes
    instance_values
  end
end

json = { name: 'bob', age: 22, awesome:true }.to_json
person = Person.new
person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
person.name            # => "bob"
person.age             # => 22
person.awesome         # => true

The default value for include_root is false. You can change it to true if the given JSON string includes a single root node.

json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
person = Person.new
person.from_json(json, true) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
person.name                  # => "bob"
person.age                   # => 22
person.awesome               # => true

Parameters

json req
include_root opt = include_root_in_json
Source
# File activemodel/lib/active_model/serializers/json.rb, line 146
      def from_json(json, include_root = include_root_in_json)
        hash = ActiveSupport::JSON.decode(json)
        hash = hash.values.first if include_root
        self.attributes = hash
        self
      end

Defined in activemodel/lib/active_model/serializers/json.rb line 146 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveModel::Serializers::JSON

Type at least 2 characters to search.

↑↓ navigate · open · esc close