flint_stone
flint_stone

Reputation: 833

parse json to object ruby

I looked into different resources and still get confused on how to parse a json format to a custom object, for example

class Resident
  attr_accessor :phone, :addr

  def initialize(phone, addr)
      @phone = phone
      @addr = addr
  end
end    

and JSON file

{
  "Resident": [
    {
      "phone": "12345",
      "addr":  "xxxxx"
    }, {
      "phone": "12345",
      "addr": "xxxxx"
    }, {
      "phone": "12345",
      "addr": "xxxxx"
    }
  ]
}

what's the correct way to parse the json file into a array of 3 Resident object?

Upvotes: 44

Views: 54380

Answers (5)

Dragas
Dragas

Reputation: 1311

If you're using ActiveModel::Serializers::JSON you can just call from_json(json) and your object will be mapped with those values.

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

Upvotes: 13

ka8725
ka8725

Reputation: 2918

We recently released a Ruby library static_struct that solves the issue. Check it out.

Upvotes: 3

JGutierrezC
JGutierrezC

Reputation: 4513

Today i was looking for something that converts json to an object, and this works like a charm:

person = JSON.parse(json_string, object_class: OpenStruct)

This way you could do person.education.school or person[0].education.school if the response is an array

I'm leaving it here because might be useful for someone

Upvotes: 109

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

The following code is more simple:

require 'json'

data = JSON.parse(json_data)
residents = data['Resident'].map { |rd| Resident.new(rd['phone'], rd['addr']) }

Upvotes: 42

user904990
user904990

Reputation:

require 'json'

class Resident
    attr_accessor :phone, :addr

    def initialize(phone, addr)
        @phone = phone
        @addr = addr
    end
end

s = '{"Resident":[{"phone":"12345","addr":"xxxxx"},{"phone":"12345","addr":"xxxxx"},{"phone":"12345","addr":"xxxxx"}]}'

j = JSON.parse(s)

objects = j['Resident'].inject([]) { |o,d| o << Resident.new( d['phone'], d['addr'] ) }

p objects[0].phone
"12345"

Upvotes: 4

Related Questions