0

我正在开发一个返回 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 > 

任何人都可以提供任何见解?难道我做错了什么?

非常感谢

4

2 回答 2

2

问题

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

解决方案

通过将 JSON 括在单引号或 Ruby 引号文字中,将其解析为字符串。例如:

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"}}]}}
于 2013-04-01T12:34:41.470 回答
0

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

尝试将':'替换为'=>',它工作正常。

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"}
于 2013-04-01T12:38:14.723 回答