parse json to object ruby

后端 未结 5 430
囚心锁ツ
囚心锁ツ 2020-12-24 07:13

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,         


        
相关标签:
5条回答
  • 2020-12-24 07:34
    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"
    
    0 讨论(0)
  • 2020-12-24 07:43

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

    0 讨论(0)
  • 2020-12-24 07:46

    The following code is more simple:

    require 'json'
    
    data = JSON.parse(json_data)
    residents = data['Resident'].map { |rd| Resident.new(rd['phone'], rd['addr']) }
    
    0 讨论(0)
  • 2020-12-24 07:46

    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
    
    0 讨论(0)
  • 2020-12-24 07:50

    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

    0 讨论(0)
提交回复
热议问题