为什么从我的Sinatra App返回的JSON会出现语法错误?

时间:2013-04-01 12:30:34

标签: ruby-on-rails json sinatra

我正在开发一个返回JSON的Sinatra应用程序,例如

  get '/clients' do

     # do stuff

     response = {
       "success" => "true",
       "msg" => "Clients successfully retrieved",
       "data" => {"clients" => @current_user.clients}
     }
     return response.to_json
  end

返回的JSON看起来像这样:

{"success":"true","msg":"Clients successfully retrieved","data":{"clients":[{"client":{"created_at":"2013-03-31T22:50:18Z","email":"test@test.com","first_name":"Marge","gender":"F","hairdresser_id":2,"id":1,"surname":"Simpson","updated_at":"2013-03-31T22:50:18Z"}}]}}

当我将其复制并粘贴到JSON解析器中时,它可以正常工作。 http://json.parser.online.fr/

但是当我启动irb并尝试使用它时,我收到了一堆错误:

1.9.3-p286 :001 > a = {"success":"true","msg":"Clients successfully retrieved","data":{"clients":[{"client":{"created_at":"2013-03-31T22:50:18Z","email":"test@test.com","first_name":"Marge","gender":"F","hairdresser_id":2,"id":1,"surname":"Simpson","updated_at":"2013-03-31T22:50:18Z"}}]}}
SyntaxError: (irb):1: syntax error, unexpected ':', expecting tASSOC
a = {"success":"true","msg":"Clients success...
           ^
(irb):1: syntax error, unexpected ',', expecting $end
a = {"success":"true","msg":"Clients successfully r...
                  ^
  from /home/[me]/.rvm/rubies/ruby-1.9.3-p286/bin/irb:13:in `<main>'
1.9.3-p286 :002 > 

任何人都能提供任何见解?我做错了吗?

非常感谢

2 个答案:

答案 0 :(得分:2)

问题

JSON不构成有效的Ruby hash。这是一个你需要用JSON#parse解析的字符串。

解决方案

通过将JSON封装在单引号或Ruby引号文字中来将其解析为String。例如:

JSON.parse %q/{"success":"true","msg":"Clients successfully retrieved","data":{"clients":[{"client":{"created_at":"2013-03-31T22:50:18Z","email":"test@test.com","first_name":"Marge","gender":"F","hairdresser_id":2,"id":1,"surname":"Simpson","updated_at":"2013-03-31T22:50:18Z"}}]}}/
=> {"success"=>"true",
 "msg"=>"Clients successfully retrieved",
 "data"=>
  {"clients"=>
    [{"client"=>
       {"created_at"=>"2013-03-31T22:50:18Z",
        "email"=>"test@test.com",
        "first_name"=>"Marge",
        "gender"=>"F",
        "hairdresser_id"=>2,
        "id"=>1,
        "surname"=>"Simpson",
        "updated_at"=>"2013-03-31T22:50:18Z"}}]}}

答案 1 :(得分:0)

您的哈希值具有键值对,表示为{key:value},但ruby使用'=&gt;'用于将键映射到值的符号。

尝试将':'替换为'=&gt;'它工作正常。

eg) a = {"success" => "true"}

如果你想将这个Json解析为ruby,那么请使用这个片段:

require 'json'
value = "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}