Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse json to object ruby

Tags:

json

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?

like image 339
flint_stone Avatar asked Oct 04 '12 08:10

flint_stone


3 Answers

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

like image 199
JGutierrezC Avatar answered Nov 07 '22 23:11

JGutierrezC


The following code is more simple:

require 'json'

data = JSON.parse(json_data)
residents = data['Resident'].map { |rd| Resident.new(rd['phone'], rd['addr']) }
like image 41
KARASZI István Avatar answered Nov 07 '22 23:11

KARASZI István


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
like image 9
Dragas Avatar answered Nov 08 '22 00:11

Dragas