JSON::ParserError: 757: unexpected token at '{
当前哈希为
1 | {"report_name"=>"Study/Control: ABIRATERONE ACETATE - 20151413355", "left_mue_start_date"=>"02-26-2015", "left_mue_end_date"=>"03-19-2015", "right_mue_start_date"=>"02-26-2015", "right_mue_end_date"=>"03-19-2015", "report_formulary_id"=>",7581", "mue"=>"true", "mue_type"=>"study/control", "chain_id"=>"1", "left_mue_formulary_ids"=>["7581"], "action"=>"create_report", "controller"=>"informatics", "user_id"=>339} |
现在我需要把它转换成适当的散列形式
1 | {"report_name" =>"Study/Control: ABIRATERONE ACETATE - 20151413355"} |
所以我尝试用json.parse来获取它,但我得到的错误如下:
1 | JSON::ParserError: 757: unexpected token at '{ |
所以如果有人知道,请帮助我。我用的是轨道3.2
您所拥有的是一个以字符串形式打印的哈希。要将其转换为哈希,请使用eval。
1 2 3 | ch ="{"report_name"=>"Study/Control: ABIRATERONE ACETATE - 20151413355", "left_mue_start_date"=>"02-26-2015", "left_mue_end_date"=>"03-19-2015", "right_mue_start_date"=>"02-26-2015", "right_mue_end_date"=>"03-19-2015", "report_formulary_id"=>",7581", "mue"=>"true", "mue_type"=>"study/control", "chain_id"=>"1", "left_mue_formulary_ids"=>["7581"], "action"=>"create_report", "controller"=>"informatics", "user_id"=>339}" hash = eval(ch) # => {"report_name"=>"Study/Control: ABIRATERONE ACETATE - 20151413355","left_mue_start_date"=>"02-26-2015","left_mue_end_date"=>"03-19-2015","right_mue_start_date"=>"02-26-2015","right_mue_end_date"=>"03-19-2015","report_formulary_id"=>",7581","mue"=>"true","mue_type"=>"study/control","chain_id"=>"1","left_mue_formulary_ids"=>["7581"],"action"=>"create_report","controller"=>"informatics","user_id"=>339} |
ps:json字符串应该如下所示,这意味着您所拥有的不是json,因此在非json字符串上使用
1 | "{"report_name":"Study/Control: ABIRATERONE ACETATE - 20151413355","left_mue_start_date":"02-26-2015","left_mue_end_date":"03-19-2015","right_mue_start_date":"02-26-2015","right_mue_end_date":"03-19-2015","report_formulary_id":",7581","mue":"true","mue_type":"study/control","chain_id":"1","left_mue_formulary_ids":["7581"],"action":"create_report","controller":"informatics","user_id":339}" |
为了避免使用
上次我遇到这个问题的时候,因为我从一个包含
UTF-8 BOM is a sequence of bytes (EF BB BF)
What's different between UTF-8 and UTF-8 without BOM?
在字符串的开头,但您知道当我们从响应中获取字符串时,该部分将不会显示或可读。我试图使用RubyJSON来解析它,但是失败了,我得到了和您相同的异常。当您得到JSON响应时,只需提醒其他人。顺便说一下,当您在JavaScript中处理它时,这不会有问题,但是在Python或Ruby语言中会有问题。
我遇到了一个类似的问题,尽管在分析""时失败了。这与使用pact.io有关。我在这里提到它,因为这是在查找我遇到的错误时排名最高的谷歌结果。在我的案例中,解决方案是在我的C应用程序中更改一个帖子的正文,这样它就不使用空字符串,而是使用一个空字符串。基本上,我在HTTP调用之前添加了这个。
1 2 | if (request.Method == HttpMethod.Post && request.Content!=null && request.Content.GetType()==typeof(StringContent) && request.Content.ReadAsStringAsync().Result == String.Empty) request.Content = new StringContent(null); |