ParserError字符串到哈希转换

时间:2012-10-16 15:50:07

标签: ruby-on-rails ruby

我需要将此字符串转换为哈希

{lhs: "1 Euro",rhs: "0.809656799 British pounds",error: "",icc: true}

我试过这种方式

JSON.parse('{lhs: "1 Euro",rhs: "0.809656799 British pounds",error: "",icc: true}'.to_s)
JSON::ParserError: 757: unexpected token at '{lhs: "1 Euro",rhs: "0.809656799 British pounds",error: "",icc: true}'

任何提示?

FYI http://www.google.com/ig/calculator?hl=en&q=1EUR=?GBP

1 个答案:

答案 0 :(得分:2)

您的字符串不是有效的JSON传输。必须引用所有密钥。

例如,这有效:

1.9.3:1 > require 'json'
 => true 

1.9.3:2 > s = '{"lhs": "1 Euro","rhs": "0.809656799 British pounds","error": "", "icc": true}'
 => "{\"lhs\": \"1 Euro\",\"rhs\": \"0.809656799 British pounds\",\"error\": \"\", \"icc\": true}" 

1.9.3:3 > JSON.parse(s)
 => {"lhs"=>"1 Euro", "rhs"=>"0.809656799 British pounds", "error"=>"", "icc"=>true}

如果您无法将哈希字符串转换为有效的JSON传输,那么这应该可以解决问题:

1.9.3:1 > s = '{lhs: "1 Euro",rhs: "0.809656799 British pounds",error: "",icc: true}'
 => "{lhs: \"1 Euro\",rhs: \"0.809656799 British pounds\",error: \"\",icc: true}" 

1.9.3:2 > s.gsub(/(?<key>\w+)\:/, '"\k<key>":')
 => "{\"lhs\": \"1 Euro\",\"rhs\": \"0.809656799 British pounds\",\"error\": \"\",\"icc\": true}"

1.9.3:3 > JSON.parse(s.gsub(/(?<key>\w+)\:/, '"\k<key>":'))
 => {"lhs"=>"1 Euro", "rhs"=>"0.809656799 British pounds", "error"=>"", "icc"=>true} 

使用抓取密钥的正则表达式:/(?<key>\w+)\:/,然后使用gsub添加引号。