简体   繁体   中英

Ruby to_json encode cyrillic into unicode

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM