0

I'm parsing some JSON from a mixed content source, and with it trying to store it with ActiveRecord.

At the moment I'm using a ton of variables:

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

Or trying to make things a little easier:

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

But this is all getting very messy, and not DRY.

I think the better way to do this would be to iterate over each element that is a hash (and therefore 'complex'), and assign it it's own object. This way, I don't have to declare a trillion variables, they can instead be assigned from the context of the JSON input.

So, I can do something like this:

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

This is inspired by what ActiveResource documents:

# 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.'

Here is the JSON, reduced for brevity's sake:

{
    "username": "robert_fitzsimmonds",
    "emails": [{
        "id_number": 1,
        "address": "[email protected]",
        "confirmed": false
    }, {
        "id_number": 2,
        "address": "[email protected]",
        "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
    }
}

Would such an iteration be the most efficient solution, or is it best to stick to long, messy variables?

1 Answer 1

1

Use the hash_dot gem if you can https://github.com/adsteel/hash_dot

Sign up to request clarification or add additional context in comments.

1 Comment

This is precisely what I was looking for! Two days of searching RDocs and GitHub, and somehow I didn't stumble upon this Gem. Thanks so much Sana.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.