0

次のような文字列があります。

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

たとえば、その部分にアクセスできるように、それを JSON オブジェクトに変換するにはどうすればよいstring["1"]ですか?

( Rails (Forms) から Javascript にデータを送るの続き)

4

1 に答える 1

1

Make sure you're rendering it appropriately in rails. The string you listed isn't valid javascript (it's using the ruby hashrocket syntax rather than JSON hash syntax):

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

or much better (relying on rails to build the json for you from a ruby hash):

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

And then fetch the json at /things.json assuming this is hooked up in your config/routes.rb file.

于 2013-06-26T03:57:26.913 に答える