ruby on rails - Why does the JSON returned from my Sinatra App give a syntax error? -
i'm developing sinatra app, returns json, e.g.
'/clients' # stuff response = { "success" => "true", "msg" => "clients retrieved", "data" => {"clients" => @current_user.clients} } return response.to_json end
the returned json looks this:
{"success":"true","msg":"clients 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"}}]}}
when copy , paste json parser, works fine. http://json.parser.online.fr/
but when fire irb , try use it, bunch of errors:
1.9.3-p286 :001 > = {"success":"true","msg":"clients 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 = {"success":"true","msg":"clients success... ^ (irb):1: syntax error, unexpected ',', expecting $end = {"success":"true","msg":"clients r... ^ /home/[me]/.rvm/rubies/ruby-1.9.3-p286/bin/irb:13:in `<main>' 1.9.3-p286 :002 >
anyone able offer insight? doing wrong?
thanks alot
problem
json doesn't constitute valid ruby hash. it's string need parse json#parse.
solution
parse json string enclosing in single quotes or ruby quote literal. example:
json.parse %q/{"success":"true","msg":"clients 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 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"}}]}}
Comments
Post a Comment