2016-01-20 59 views
-5

我想解析一个发布请求返回的JSON。我有以下代码:JSON.parse不工作

response = RestClient.post "http://localhost:4567", request.body.read,:content_type => :json, :accept => :json 
result = JSON.parse('#{response.body}') 

它给我下面的错误:

JSON::ParserError - 757: unexpected token at '#{response.body}': 

我已经检查了response.body返回正确的JSON。如果我复制JSON的内容并将其粘贴到JSON.parse中,它可以很好地工作。但是,当我使用该变量它不起作用。

+1

什么是你的问题? – sawa

+0

如何解决它以使解析工作? –

+0

你可以显示什么'response.body'看起来像? – Atri

回答

4

单引号不会扩展插值。 JSON.parse(response.body)JSON.parse("#{response.body}")应能工作。

+0

JSON.parse(response.body)不起作用。它告诉我:错误TypeError:没有将数组隐式转换为字符串。我用is_a?检查response.body是否是一个字符串,输出是否为真。 –

+0

如果'response.body'是一个数组,则@JackLi使用'response.body.to_s'。 – Atri

+0

@Atri response.body是一个字符串。我检查了is_a? –

1

既然你提到response.body是一个字符串,你可以做JSON.parse(response.body)。你不需要插入它。

根据您的评论给的例子,它工作正常:

2.1.2-perf :007 > s = '{ "age_result": [ { "column_id": [ "B01001003", "B01001027" ], "name": "Under 5 years", "number": [ 6774.0, 6416.0 ] }, { "column_id": [ "B01001004", "B01001028" ], "name": "5 to 9 years", "number": [ 5981.0, 6470.0 ] }] }' 
=> "{ \"age_result\": [ { \"column_id\": [ \"B01001003\", \"B01001027\" ], \"name\": \"Under 5 years\", \"number\": [ 6774.0, 6416.0 ] }, { \"column_id\": [ \"B01001004\", \"B01001028\" ], \"name\": \"5 to 9 years\", \"number\": [ 5981.0, 6470.0 ] }] }" 
2.1.2-perf :008 > JSON.parse(s) 
=> {"age_result"=>[{"column_id"=>["B01001003", "B01001027"], "name"=>"Under 5 years", "number"=>[6774.0, 6416.0]}, {"column_id"=>["B01001004", "B01001028"], "name"=>"5 to 9 years", "number"=>[5981.0, 6470.0]}]}