2012-10-04 16 views
16

nesne ve hala ne örnekayrıştırma json Farklı kaynaklara baktım Ruby

class Resident 
    attr_accessor :phone, :addr 

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

ve JSON dosyası

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

için, özel bir nesneye bir json biçimi ayrıştırmak için nasıl karıştı olsun json dosyasını 3 Resident nesnesi dizisine ayırmak için doğru yol? i Bir nesneye json dönüştüren şey arıyordum

require 'json' 

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

Bu JSON'u bir yakut karma olarak ayrıştırın, daha sonra bu karma adımı yürütün ve Yerleşik nesneler oluşturun. –

+0

@SergioTulentsev, JSON.parse (jsonfile) kullanılarak mı? –

+0

flint_stone: Evet, tam olarak. –

cevap

26

şu kod daha basittir

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

Bu şekilde Yanıt bir dizi

ise person.education.school veya person[0].education.school yapabilirdiniz Burada bırakıyorum çünkü birisi

4
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

Bu kötü değil, her biri yerine “Numaralandırılabilir # harita” yı kullanabilirsiniz. –

+0

'inject 'daha iyidir :) –

+0

Fikrimi bir cevap olarak ekledim. –

36

Bugün ve bu bir cazibe gibi çalışır:

+4

imho bunu yapmanın en iyi yolu. – Alu

+1

Kullanışlı, ancak özel bir nesne değil. –

2

için yararlı olabilir Son zamanlarda sorunu çözen bir Ruby kitaplığı static_struct yayınladık. Check it out.

0

ActiveModel::Serializers::JSON kullanıyorsanız, from_json(json) numaralı telefonu arayabilir ve nesneniz bu değerler ile eşlenecektir.

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