如何将字符串转换为JSON对象?

时间:2013-06-26 03:30:56

标签: javascript jquery ruby-on-rails json

我有一个这样的字符串:

//string
" { "1" => "one stuff\n print 'hi'.. ",
          "2" => "two stuff\n print 'by' "} "

如何将其转换为JSON对象,以便我可以使用例如string["1"]

(后续行动 Sending Data to Javascript from Rails (Forms)

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文件中。