1

i am finding a method to change a key's name of json object that is a hash on ruby like below

source

{ "a" => "b", "b" => "bb" }

result

{ "c" => "b", "b" => "bb" }

got a nice idea ?

1

3 Answers 3

1
source = { "a" => "b", "b" => "bb", "c" => "lol" }
PATTERN = { "a" => "c", "c" => "e" }
source.inject({}) do |new_hash, (k, v)|
  key = PATTERN[k] || k
  new_hash[key] = v
  new_hash
end
#=> { "c" => "b", "b" => "bb", "e" => "lol" }
Sign up to request clarification or add additional context in comments.

Comments

1

If you need this functionality frequently, you can extend the Ruby Hash class.

Implementation would vary from ruby version to version, but roughly something like this:

class Hash
  module ClassMethods
    def self.replace_key(old_key, new_key)
     self[new_key] = self[old_key]
     self.delete(old_key)
    end
  end
end

Basically, creating a new key,value pair in the Hash using the new key and old value. Then deleting the original pair.

Note: Operations like this on large hashes are inadvisable from a performance perspective.

Comments

0

If you are serializing ActiveRecord or ActiveModel object, you can overwrite as_json method of the class. Like so:

class Foo < ActiveRecord::Base
  def as_json(options = { })
     super((options.select {|k,v| k.to_s != "a" }).merge("c" => options["a"]))
  end
end

Comments

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.