Reputation: 130
I have a hash object with cyrilic text like this
payload = {'date': "30",'name': 'Тест','phone': "71234567890",'sum': "0",'offer_id': "1"}
I need to convert it to json and send to php api service like this
{"date":"30","name":"\u0422\u0435\u0441\u0442","offer_id":"1","phone":"71234567890","sum":"0"}
But to_json
returns me
{"date":"30","name":"Тест","offer_id":"1","phone":"71234567890","sum":"0"}
How do I encode cyrilic into unicode in that case? Do I need to pass options to to_json
method?
Upvotes: 0
Views: 273
Reputation: 121000
There definitely should be a more elegant solution, but with String#dump
the below would work.
payload.to_json.dump.
gsub('\\"', '"').
sub(/\A\s*"\s*|\s*"\s*\z/, '')
Check:
require 'digest/md5'
require 'json'
payload = {'date': "30",'name': 'Тест', 'offer_id': "1", 'phone': "71234567890",'sum': "0",}
expected_json = '{"date":"30","name":"\u0422\u0435\u0441\u0442","offer_id":"1","phone":"71234567890","sum":"0"}'
dumped_json =
payload.to_json.dump.
gsub('\\"', '"').
sub(/\A\s*"\s*|\s*"\s*\z/, '')
puts expected_json
puts
puts dumped_json
puts
puts expected_json == dumped_json
puts Digest::MD5.hexdigest(expected_json)
puts Digest::MD5.hexdigest(dumped_json)
Please be aware that there is no guarantee in the order of elements in the JSON, so checking MD5 is generally a bad idea.
Upvotes: 1