ToddT ToddT - 1 year ago 110
JSON Question

Hash rocket vs colon in render json:

I am rendering a response to a

request from a webhook. I just realized that when I
render json: thingee
and I log
it has hash rockets which are not valid json.

I've seen where people
the hash and it looks fine, but that's not what I'm doing, I'm rendering a hash as JSON in response to a POST..

When rendered, my hash looks like this:

{"rates"=>[{"service_name"=>"Standard", "service_code"=>"f48",
"total_price"=>"390",},{"service_name"=>"Expedited", "service_code"=>"f34",

But I need it to be valid JSON and look like this:

{"rates":[{"service_name":"Standard", "service_code":"f48",
"total_price":"390",},{"service_name":"Expedited", "service_code":"f34",


max max
Answer Source

Don't worry so much. Its perfectly fine.

In Ruby the hashrocket syntax needs to be used whenever you want to have a hash key that is not a symbol:

irb(main):002:0> { foo: 1, 'baz': 2 }
=> {:foo=>1, :baz=>2} # coerces 'baz' into a symbol
irb(main):003:0> { foo: 1, 'baz' => 2 }
=> {:foo=>1, "baz"=>2}

However when you pass the hash render: { json: @foo } the hash is passed to JSON.generate which converts the ruby hash to valid JSON.

irb(main):006:0> JSON.generate({ "foo" => 1, "baz" => 2 })
=> "{\"foo\":1,\"baz\":2}"
irb(main):007:0> JSON.generate({ foo: 1, baz: 2 })
=> "{\"foo\":1,\"baz\":2}"
irb(main):008:0> { foo: 1, baz: 2 }.to_json
=> "{\"foo\":1,\"baz\":2}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download