0

I'm currently trying to sync my database up with another database with Json, but I'm running into issues with a key they're using.

def sync
    url = '...' # Returns "{ "class": 20, "user": "John" }"
    uri = URI(url)
    response = Net::HTTP.get(uri)
    response_hash = JSON.parse(response)
...

They use the keyword 'class' in their response, but I don't think I'm allowed that, so I have mine as 'cls'. Now, if I try to create a new User, I'll get an error because it cannot map 'class' to anything.

I've been trying to change the key to match my new key, but have been unable to get that to work.

Using answers such as has no effect for some reason.

pattern = { "class" => "cls" }

response_hash.inject({}) do |new_hash, (k, v)|
  key = pattern[k] || k
  new_hash[key] = v
  new_hash
end

But I did notice that I have a Hash, whereas some of the examples created a HashWithIndifferentAccess, so they could do response_hash[:class], but mine would only return nil.

What would be the best solution for this problem? Ideally, I wouldn't have to remap any keys, and could just throw the Json into my database.

Thanks for your help.

1 Answer 1

2

Simply do this

response_hash['cls'] = response_hash.delete('class')

The result would be { :cls => 20, :user => "John" } which you may directly throw into your database.

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

5 Comments

I tried what you've suggested, but it's still giving me the same results. I'm unsure why. 'cls' is not there, and 'class' still is. Oh, but I tried with creating a HashWithIndifferentAccess from response_hash, then calling that, and that works.
Small question, if I wanted a nested Object, how would I do that? Say the 'response' contains an Object, and I want to map that to a Model. Passing the hash fails because it expects a Model, but trying to create it early fails because it requires the parent to be created.
Try using accepts_nested_attributes_for. See this answer for reference : stackoverflow.com/a/23674227/755421
I tried adding that, but still get the same issue. MyObject expected, got Hash
You'll have to do a lot more than just adding that statement. Read the answer to get a complete sense of how accepts_nested_attributes_for works.

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.