当我尝试将ruby字符串解析为JSON时,self.id会引发有关无效令牌的错误。
JSON.parse "{ 'description' => 'client #{self.id} has been deleted.' }"
我在对象周围尝试单引号,但这不会导致插值。如何同时获得插值和成功的JSON解析?
答案 0 :(得分:3)
这里的问题是即使没有插值,你的字符串也是无效的JSON。
"{ 'description' => 'client has been deleted.' }"
以下是有效的JSON:
'{ "description": "client has been deleted." }'
请注意键和值周围的双引号,以及冒号:
,而不是特定于ruby的散列火箭=>
。
也许您正在尝试将Ruby哈希转换为json?
require 'json'
id = 5
x = { 'description' => "client #{id} has been deleted." }.to_json
puts x # '{ "description": "client 5 has been deleted." }'
答案 1 :(得分:1)
好像你只是想从字符串中运行一些ruby。因此,假设self.id为1:
eval "{ 'description' => 'client #{self.id} has been deleted.' }"
会屈服:
=> {"description"=>"client 1 has been deleted."}