如何在没有EVAL的情况下将字符串转换为哈希 [英] How to convert string to hash WITHOUT EVAL

查看:164
本文介绍了如何在没有EVAL的情况下将字符串转换为哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串。 { response_code => SUCCESS, authorisation_result => Approved, transaction_number => 1234567, receipt_number => 999999,:cents => 100}作为值存储在hstore在postgresql中。

I have a string. {"response_code"=>"SUCCESS", "authorisation_result"=>"Approved", "transaction_number"=>"1234567", "receipt_number"=>"999999", :cents=>100} that is stored as a value in hstore in postgresql.

所以它是一个原始字符串,而不是YAML或JSON。

我很想知道如何将值返回到用于插入记录。

So it's a raw string not a YAML or a JSON.
I was wonering how to get the value back to the hash that was used to insert the record.

使用EVAL的想法吓到我了,因为这里有使用输入的潜力。

The idea of using EVAL scares the hell out of me, because there is potential for use input here.



这个问题似乎是回答那里不与问题啮合。它仅提供eval作为解决方案。 (我不明白如何将答案标记为答案)


This question might seem to be a replica of How to convert a string to a hash in ruby/rails without using eval?, but the answer there doesn't mesh with the question. It only offers eval as the solution. (I don't understand how the answer was marked as the answer)

推荐答案

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}

这篇关于如何在没有EVAL的情况下将字符串转换为哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆