Reputation: 1399
I have the following JSON:
{
my_json: {
id: 1,
name: "John"
}
}
How can I customize key name via parameterized like:
def jsonize(custom_key="id")
{
my_json: {
"#{custom_key}": 1,
name: "John"
}
}
end
To be output with:
Scenario 1:
=> jsonize
OUTPUT:
{
my_json: {
id: 1,
name: "John"
}
}
Scenario 2:
=> jsonize("value")
OUTPUT:
{
my_json: {
value: 1,
name: "John"
}
}
Upvotes: 2
Views: 360
Reputation: 198334
The hash-rocket syntax has been in Ruby since ancient times:
{ :foo => 1, "bar" => 2 }
Ruby 1.9 (I think) introduced a new colon shortcut syntax just for symbols (while keeping the hash-rocket general for any key type):
{ foo: 1, "bar" => 2 }
Ruby 2.2 (I think) introduced the possibility of symbolizing a string in this syntax:
{ "foo": 1, "bar" => 2 }
All of these do the same thing. What you are doing is perfectly grammatical Ruby code -- in a sufficiently new Ruby. In older Rubies, you will need to use the old reliable hash-rocket syntax:
{ "foo".to_sym => 1, "bar" => 2 }
Now that you actually have a string, you can do normal interpolation:
{ "f#{'o' * 2}".to_sym => 1, "bar" => 2 }
In your case, you could write
{ "#{custom_key}".to_sym => 1 }
However, all of this is completely unnecessary, since you can just write simply this, in any Ruby:
{ custom_key.to_sym => 1 }
Even better, since you're just turning everything into JSON immediately after, you don't even need symbolised keys; so these two expressions will have identical results:
{ custom_key.to_sym => 1 }.to_json
{ custom_key => 1 }.to_json
(Also note that what you state as examples of JSON -- both input and output -- are, in fact, not JSON, nor would .to_json
output such. In JSON, as opposed to plain JavaScript object literal, keys must be double-quoted, and that is how to_json
would produce it. Your input is a Ruby valid Ruby hash, though.)
Upvotes: 1
Reputation: 23671
You can just convert it to symbol
and use hash_rocket
syntax you will get the expected result
def jsonize(custom_key = "id")
{
my_json: {
custom_key.to_sym => 1,
name: "John"
}
}
end
#=> jsonize('foo')
#=> {
#=> :my_json => {
#=> :foo => 1,
#=> :name => "John"
#=> }
#=> }
Upvotes: 0
Reputation: 1652
You can use ":" to separate symbolic keys and values, use "=>" in your example:
def jsonize(custom_key="id")
{
my_json: {
"#{custom_key}" => 1,
name: "John"
}
}
end
Upvotes: 1