1

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

{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}'

任何提示?

仅供参考 http://www.google.com/ig/calculator?hl=en&q=1EUR=?GBP

4

1 回答 1

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添加引号。

于 2012-10-16T15:55:37.407 回答