I am rendering a response to a POST request from a webhook. I just realized that when I render json: thingee and I log thingee it has hash rockets which are not valid json.
I've seen where people puts 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",
"total_price"=>"640"}]}
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",
"total_price":"640"}]}
Thanks
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With