0

因此,我使用 to_json 将 Ruby on Rails 中的对象序列化为 JSON 格式。产生的输出是:

'{"description":"---\n- Nulla adipisci quia consequuntur nam ab et. Eius enim ad aut. Asperiores recusandae\n  labore exercitationem.\n    quos provident.\n","id":295,"name":"Animi enim dolorem soluta eligendi inventore quia distinctio magni.","privacy":0,"updated_at":"2012-11-18T22:24:17Z","user_id":1}'

这需要由 JSON.parse 解析以反序列化客户端 javascript 中的对象。\n目前,由于“描述”值中的换行符,这失败了。我尝试使用gsub("\n","\\n")和其他排列对字符进行适当的编码,但我似乎找不到正确匹配换行符(并且只有换行符)的字符串或正则表达式。我已经尝试过/\n/, '\n', "\n", "\\n"(由于某种原因,这匹配字符串上的任何地方)/\\n/等等,但找不到任何东西。有什么我想念的想法吗?

更新:这是我试图用来填充 javascript 对象的代码(javascript,但嵌入了 ruby​​)(它在 ERB 视图中,因此是尖括号):

var object = JSON.parse('<%= raw @object.to_json %>');

to_json在我的目标代码中没有被覆盖,只是标准的 rails 方法。

4

2 回答 2

1
j = %Q!{"description":"---\n- Nulla adipisci quia consequuntur nam ab et. Eius enim ad aut. Asperiores recusandae\n  labore exercitationem.\n    quos provident.\n","id":295,"name":"Animi enim dolorem soluta eligendi inventore quia distinctio magni.","privacy":0,"updated_at":"2012-11-18T22:24:17Z","user_id":1}!
j.gsub! /\n/, '\\n'
JSON.parse j
# => {"description"=>"---\n- Nulla adipisci quia consequuntur nam ab et. Eius enim ad aut. Asperiores recusandae\n  labore exercitationem.\n    quos provident.\n", "id"=>295, "name"=>"Animi enim dolorem soluta eligendi inventore quia distinctio magni.", "privacy"=>0, "updated_at"=>"2012-11-18T22:24:17Z", "user_id"=>1}

让您的生活更轻松,当您需要操作转义字符时,请在转义字符周围使用单引号。


更新后……</p>

var object = JSON.parse('<%= raw @object.to_json.gsub(/\n/, %q!\\n!) %>');
于 2013-01-25T08:45:20.043 回答
1

你的 JSON 包含一个 YAML 字符串,所以不要浪费时间尝试删除换行符,否则你会让事情变得更糟,或者至少会让你自己做太多的工作。

require 'json'
require 'yaml'

json = '{"description":"---\n- Nulla adipisci quia consequuntur nam ab et. Eius enim ad aut. Asperiores recusandae\n  labore exercitationem.\n    quos provident.\n","id":295,"name":"Animi enim dolorem soluta eligendi inventore quia distinctio magni.","privacy":0,"updated_at":"2012-11-18T22:24:17Z","user_id":1}'

hash = JSON[json]
puts YAML.load(hash['description'])

输出:

Nulla adipisci quia consequuntur nam ab et. Eius enim ad aut. Asperiores recusandae labore exercitationem. quos provident.

在解码回 Ruby 哈希后,JSON 看起来像:

{“描述”=>
  "---\n- Nulla adipisci quia consequuntur nam ab et. Eius enim ad aut. Asperiores recusandae\n labore exercitationem.\n quos provident.\n",
 “身份证”=> 295,
 "name"=>"Animi enim dolorem soluta eligendiinvente quia distinctio magni.",
 “隐私”=>0,
 "updated_at"=>"2012-11-18T22:24:17Z",
 “用户 ID”=>1}

要将其转换回真正的 JSON 字符串,而description不是编码为 YAML,请使用:

hash['description'] = YAML.load(hash['description']).shift
puts hash.to_json

现在看起来像:

{"description":"Nulla adipisci quia consequuntur nam ab et. Eius enim ad aut. Asperiores recusandae labore exercitationem. quos provident.","id":295,"name":"Animi enim dolorem soluta eligendi inventore quia distinctio magni.","privacy":0,"updated_at":"2012-11-18T22:24:17Z","user_id":1}
于 2013-01-25T09:44:15.977 回答