【问题标题】:JSON.parse not working [closed]JSON.parse 不工作 [关闭]
【发布时间】:2016-04-26 20:30:08
【问题描述】:

我正在尝试解析 post 请求返回的 JSON。我有以下代码:

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 中,它会完美运行。但是,当我使用该变量时,它不起作用。

【问题讨论】:

  • 你的问题是什么?
  • 如何修复它以使解析工作?
  • 你能展示一下response.body 的样子吗?
  • @Atri 太长了,不适合放在这里。 { "age_result": [ { "column_id": [ "B01001003", "B01001027" ], "name": "5 岁以下", "number": [ 6774.0, 6416.0 ] }, { "column_id": [ "B01001004 ", "B01001028" ], "name": "5 到 9 年", "number": [ 5981.0, 6470.0 ] }, { "column_id": [ "B01001005", "B01001029" ] } 这是其中的一部分。
  • @JackLi 检查我的回答是否有帮助。

标签: ruby json


【解决方案1】:

单引号不展开插值。 JSON.parse(response.body)JSON.parse("#{response.body}") 应该可以工作。

【讨论】:

  • JSON.parse(response.body) 不起作用。它告诉我:错误类型错误:没有将数组隐式转换为字符串。我用is_a?检查 response.body 是否为字符串且输出为真。
  • @JackLi 使用 response.body.to_s 如果 response.body 是一个数组。
  • @Atri response.body 是一个字符串。我与 is_a 核对过?
  • @JackLi 你能把response.body的内容打印出来吗?
【解决方案2】:

既然您提到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]}]}

【讨论】:

    猜你喜欢
    • 2015-07-23
    • 1970-01-01
    • 2023-03-24
    • 2013-02-04
    • 2014-05-04
    • 2012-10-08
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多