我有一个这样的字符串:
//string
" { "1" => "one stuff\n print 'hi'.. ",
"2" => "two stuff\n print 'by' "} "
如何将其转换为JSON对象,以便我可以使用例如string["1"]
?
答案 0 :(得分:1)
确保在rails中正确渲染它。您列出的字符串不是有效的javascript(它使用ruby hashrocket语法而不是JSON哈希语法):
class ThingsController < ApplicationController
def index
respond_to do |format|
format.json do
str = ' { "1": "one stuff\n print \'hi\'.. ", "2": "two stuff\n print \'bye\' "} '
render json: str
end
end
end
end
或更好(依靠rails从ruby哈希为你构建json):
class ThingsController < ApplicationController
def index
respond_to do |format|
format.json do
obj = {1 => "one stuff\n print 'hi'", 2 => "two stuff\n print 'bye'" }
render json: obj
end
end
end
end
然后在/things.json
处获取json,假设它已连接到您的config/routes.rb
文件中。