araratan araratan - 2 months ago 25
Ruby Question

Parameterized JSON key naming

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"
}
}

Answer

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"
#=>     }
#=> }