您的字符串不是有效的 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
添加引号。