且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有EVAL的情况下将字符串转换为哈希

更新时间:2022-11-04 10:43:19

Ruby哈希看起来与JSON非常相似,因此会适合您的示例:

Ruby hashes look pretty similar to JSON, so this would work for your example:

require 'json'

str = "{\"response_code\"=>\"SUCCESS\", \"authorisation_result\"=>\"Approved\", \"transaction_number\"=>\"1234567\", \"receipt_number\"=>\"999999\", :cents=>100}"

JSON.parse str.gsub(/:(\w+)/){"\"#{$1}\""}.gsub('=>', ':')
# => {"response_code"=>"SUCCESS", "authorisation_result"=>"Approved", "transaction_number"=>"1234567", "receipt_number"=>"999999", "cents"=>100}