将 json 解析为对象 ruby
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12723094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parse json to object ruby
提问by flint_stone
I looked into different resources and still get confused on how to parse a json format to a custom object, for example
例如,我查看了不同的资源,但仍然对如何将 json 格式解析为自定义对象感到困惑
class Resident
attr_accessor :phone, :addr
def initialize(phone, addr)
@phone = phone
@addr = addr
end
end
and JSON file
和 JSON 文件
{
"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?
将 json 文件解析为 3 个常驻对象数组的正确方法是什么?
回答by JGutierrezC
Today i was looking for something that converts json to an object, and this works like a charm:
今天我正在寻找将 json 转换为对象的东西,这就像一个魅力:
person = JSON.parse(json_string, object_class: OpenStruct)
This way you could do person.education.schoolor person[0].education.schoolif the response is an array
这样你就可以做person.education.school或者person[0].education.school如果响应是一个数组
I'm leaving it here because might be useful for someone
我把它留在这里是因为可能对某人有用
回答by KARASZI István
The following code is more simple:
下面的代码更简单:
require 'json'
data = JSON.parse(json_data)
residents = data['Resident'].map { |rd| Resident.new(rd['phone'], rd['addr']) }
回答by flint_stone
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"
回答by Dragas
If you're using ActiveModel::Serializers::JSONyou can just call from_json(json)and your object will be mapped with those values.
如果您正在使用,ActiveModel::Serializers::JSON您只需调用from_json(json),您的对象就会映射到这些值。
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
回答by ka8725
We recently released a Ruby library static_structthat solves the issue. Check it out.
我们最近发布了一个 Ruby 库static_struct来解决这个问题。检查一下。

