Reputation: 14277
What's the best way to get pretty, Rubified hash keys?
Ie. someKey
becomes some_key
.
Hashie::Trash -- impossible without first defining each key, ie. property :some_key, from: :someKey
-- not very pretty.
https://github.com/tcocca/rash -- unfortunately breaks Hashie::Extensions::DeepFetch which I intend to use later on.
Rails ActiveSupport's underscore
-- unclear how to apply this to my use case.
Live demo app: http://runnable.com/U-QJCIFvY2RGWL9B/pretty-json-keys
class MainController < ApplicationController
def index
@json_text = <<END
...
END
response = JSON.parse(@json_text)['products']
@products = []
response.each do |product|
@products << product['salePrice']
# Seeking the best way to make this say:
# @products << product['sale_price']
end
end
end
Upvotes: 0
Views: 171
Reputation: 46960
Well, you can always translate to a new hash:
def self.prettify(x)
x.is_a?(Hash) ? Hash[ x.map{|k,v| [k.underscore, prettify(v)]} ] :
x.is_a?(Array) ? x.map{|v| prettify(v) } : x
end
pretty_json_hash = prettify(JSON.parse(@json_text))
NB: Success with Rails will be hard to come by if you can't write code at this level.
Upvotes: 1