Ruby / Rails - 在复杂(嵌套)JSON元素上进行交互以创建对象

时间:2015-12-24 01:02:18

标签: ruby-on-rails ruby json activerecord

我正在从混合内容源解析一些JSON,并尝试使用ActiveRecord存储它。

目前我正在使用大量变量:

json['settings']['newsletters']['weekly']
json['info']['address']['city']

或者试图让事情变得更容易:

newsletters = json['settings']['newsletters']
newsletters['weekly']
address = json['info']['address']
address['city']

但这一切都变得非常混乱,而不是干。

我认为更好的方法是迭代每个作为哈希的元素(因此是“复杂的”),并为它分配它自己的对象。这样,我不必声明万亿变量,而是可以从JSON输入的上下文中分配它们。

所以,我可以这样做:

user = json['input']
user.settings.newsletters.weekly
user.info.address.city

这受到ActiveResource文件的启发:

# Any complex element (one that contains other elements) becomes its own object:
#
# {"id":1,"first":"Tyler","address":{"street":"Paper St.","state":"CA"}}
tyler = Person.find(1)
tyler.address  # => <Person::Address::xxxxx>
tyler.address.street  # => 'Paper St.'

这是JSON,为了简洁而减少:

{
    "username": "robert_fitzsimmonds",
    "emails": [{
        "id_number": 1,
        "address": "robert_fitzsimmonds@yahoo.com",
        "confirmed": false
    }, {
        "id_number": 2,
        "address": "robert_fitzsimmonds@gmail.com",
        "confirmed": true
    }],
    "settings": {
        "marketing": {
            "main": true,
            "weekly": false,
            "daily": false
        },
        "language": "English"
    },
    "info": {
        "address": {
            "line_1": "31 Mole Road",
            "line_2": "",
            "city": "London",
            "post_code": "NE4 5RJ"
        },
        "shared_account": false
    }
}

这样的迭代是否是最有效的解决方案,还是最好坚持使用长而凌乱的变量?

1 个答案:

答案 0 :(得分:1)

如果可以https://github.com/adsteel/hash_dot

,请使用hash_dot gem