JSON::ParserError: 757: unexpected token at '{ - ruby-on-rails

the current hash is
{\"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}
now I need to convert it in proper hash like
{"report_name" => "Study/Control: ABIRATERONE ACETATE - 20151413355"}
so I am trying to get it with JSON.parse but I am getting error like:
JSON::ParserError: 757: unexpected token at '{
So if someone know about that so please help me.
and I am using Rails 3.2

What you have is a hash printed as String. To convert it into a Hash use 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}"
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: A JSON string should look as follows, meaning what you have is not JSON and hence you got JSON::ParserError for using JSON.parse on a non-JSON string :
"{\"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}"

To avoid using eval you could use JSON.parse ch.gsub('=>', ':') this way you will get a HASH from your HASH stored as STRING

Last time when I got this issue, since the json file that I got from a API that contains a BOM
UTF-8 BOM is a sequence of bytes (EF BB BF)
What's different between UTF-8 and UTF-8 without BOM?
at the beginning of that string, but you know that part wouldn't display or as readable when we got the string from response. I try to use Ruby JSON to parse it, but I failed, I got the same exception with yours. just a reminder for others, when you get a Json response. By the way, this would be no problem while you are handling that in javascript, but with problems in Python or Ruby languages.

I ran into a similar problem, though it was failing while parsing \"\". This is in regards to using Pact.IO. I mention it here since this is the highest ranked Google result while looking for the error I encountered. The solution in my case was to change the body of a POST in my C# application so that it wasn't using empty string, but a null string. Basically I added this before my HTTP call.
if (request.Method == HttpMethod.Post && request.Content!=null && request.Content.GetType()==typeof(StringContent) && request.Content.ReadAsStringAsync().Result == String.Empty)
request.Content = new StringContent(null);

Related

Can't correctly parse JSON fixture in tests

I'm using Test::Unit in an old Rails app (3.2.22) and I'm trying to test a service class that hits an external api.
I'm using webmock and trying to get a json file fixture working, but I keep getting parsing errors from the json file.
My test stub looks like this:
response_data = fixture_file_upload('easypost/order_response.json')
stub_request(:post, 'https://api.easypost.com/v2/orders').
to_return(:status => 200, :body => File.read(response_data))
My order_response.json file looks like this:
{
'mode':'test',
'reference':'Order',
'is_return':false,
'options':{'currency':'USD','label_date':null}
}
When I run the tests, I get a parse error:
JSON::ParserError: 757: unexpected token at '{'mode':'test','reference':'Order','is_return':false,'options':{'currency':'USD','label_date':null}}'
What is going on?
UPDATE:
Got it working by using double quotes in the JSON file:
{
"mode":"test",
"reference":"Order",
"is_return":false,
"options":{"currency":"USD","label_date":null}
}
Could anyone explain why this is necessary?
From the fine specification:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.
and and object is a set of key/value pairs where the keys are strings:
That means that this:
{
'mode':'test',
'reference':'Order',
'is_return':false,
'options':{'currency':'USD','label_date':null}
}
is not JSON because JSON strings use double quotes and only double quotes, that's just something that sort of looks like JSON. When you switch to double quotes for your strings:
{
"mode":"test",
"reference":"Order",
"is_return":false,
"options":{"currency":"USD","label_date":null}
}
then you have JSON and everything should work.
This is to make it simpler and to avoid having to have another escape method for javascript reserved keywords
I think this post might be helpful in understanding the need for quotations (and also where I found the above quote): JSON Spec - does the key have to be surrounded with quotes?

String will not convert to JSON

I have a string passed to through a variable. I'm trying to convert it to a JSON so I can break it down, but I keep getting a JSON Parser Error.
This is the string passed to me (originally from an API, so it should be formatted correctly):
[{"FlightSegment"=>[{"DepartureAirport"=>{"LocationCode"=>"LAX"}, "ArrivalAirport"=>{"LocationCode"=>"FLL"}, "MarketingAirline"=>{"Code"=>"NK"}, "ArrivalTimeZone"=>{"GMTOffset"=>-4}, "TPA_Extensions"=>{"eTicket"=>{"Ind"=>true}}, "StopQuantity"=>0, "ElapsedTime"=>286, "ResBookDesigCode"=>"U", "MarriageGrp"=>"O", "Equipment"=>{"AirEquipType"=>319}, "DepartureDateTime"=>"2015-09-18T21:00:00", "ArrivalDateTime"=>"2015-09-19T04:46:00", "FlightNumber"=>310, "OnTimePerformance"=>{"Level"=>7}, "OperatingAirline"=>... it goes on for a while, but repeating itself.
and the code I'm trying to use:
<% parsed_list = JSON.parse(#body) %>
<%= parsed_list %>
Unfortunatley I keep getting an unexpected token:
399: unexpected token at '{"FlightSegment"=>[{"DepartureAirport"=>{"LocationCode"=>"LAX"}, "ArrivalAirport"=>{"LocationCode"=>"FLL"}, "MarketingAirline"=>{"Code"=>"NK"}, "ArrivalTimeZone"=>{"GMTOffset"=>-4}, "TPA_Extensions"=>{"eTicket"=>{"Ind"=>true}}, "StopQuantity"=>0, "ElapsedTime"=>286, "ResBookDesigCode"=>"U", "MarriageGrp"=>"O", "Equipment"=>{"AirEquipType"=>319}, "DepartureDateTime"=>"2015-09-18T21:00:00", "ArrivalDateTime"=>"2015-09-19T04:46:00", "FlightNumber"=>310, "OnTimePerformance"=>{"Level"=>7}, "OperatingAirline"=>{"FlightNumber"=>310, "Code"=>"NK"}, "DepartureTimeZone"=>{"GMTOffset"=>-7}}], "ElapsedTime"=>286}
Any thoughts?
Thank you!
#body.to_json
As Victor says, it's not a json, it's ruby hash

rails decode json cyrrilic string

I have such string example, which i get from json (cp1251):
Ôèëüòð ìàñëÿíûé OPEL/GM/DAEWOO
which mean:
Фильтр масляный OPEL/GM/DAEWOO
this tool http://www.artlebedev.ru/tools/decoder/ say that i must use CP1252 → CP1251 decoder. I try it so:
my_string.force_encoding('cp1252').force_encoding('1251')
but it didn't solve my problem. What i do wrong?
how could i convert to normall view my json cyrrillic string in RoR?
i get json from url so:
jsonAE = JSON.load(open('http://******/portal.api?l=*****&p=Sih2*****&act=price_by_nr_firm&nr='+article_nr+'&oe=true'))
from json i get:
{"result":[{"nr":"OC90","brand":"Knecht","name":"Фильтр масляный OPEL/GM/DAEWOO","stock":"-","delivery":"не известно","minq":"1","upd":"16.03.15 23:40","price":"130.34","currency":"руб."},{"nr":"OC90","brand":"Knecht","name":‌​"Фильтр масляный OPEL/GM/DAEWOO","stock":"-","delivery":"не известно","minq":"1","upd":"17.03.15 00:05","price":"130.34","currency":"руб."}]}
but it turn's to something bad with JSON.load
▶ puts 'Ôèëüòð ìàñëÿíûé OPEL/GM/DAEWOO'
.encode(Encoding::CP1252)
.force_encoding(Encoding::CP1251)
.encode(Encoding::UTF_8)
#⇒ Фильтр масляный OPEL/GM/DAEWOO
The string in ruby is suspected to be utf8ed. So, the first action is to inform ruby that the string is actually in one-byte. Than we say “hey, don’t care, I know this one-byte is actually cyrillic.” And, finally, turn it back to utf-8.
Hope it helps.

JSON string to rails hash

I'm on Rails 2.3 and I'm trying to convert a string that is JSON-formatted to a Rails hash. However, when I use JSON.parse I get a JSON string without the delimiters:
{"source_id":40007,"object":"86088947610496.1","coursewalk_id":"86088947610477.1","description":"","image_uri":"db\/db-files\/
Image_2011-09-24_14.37.37__0000.jpg","latitude":"38.0113439821061","letter":"","letter_A":"","letter_B":"","letter_C":"","lett
er_D":"","letter_E":"","letter_F":"","longitude":"-78.7576854509104","number":"1","mcw_id":71}
Results of JSON.parse:
number1letter_Bcoursewalk_id86088947610477.1letter_Clatitude38.0113439821061letter_Dletter_Eletter_Fmcw_id71longitude-78.75768
54509104letterdescriptionobject86088947610496.1source_id40007letter_Aimage_uridb/db-files/Image_2011-09-24_14.37.37__0000.jpg
Code:
puts string_to_parse
fence_parsed = JSON.parse(string_to_parse)
puts fence_parsed
Any ideas?
Thanks,
Nick
That's just because you're using "puts". If you just type fence_parsed, or p fence_parsed you'll get what you're looking for. puts calls to_s. I hope this clears it up for you, if not let me know and I'll elaborate.

Can't turn array into a string error

I have a simple call
JSON.parse(Panda.get("/videos/#{self.panda_video_id}/encodings.json"))
Which returns :
can't convert Array into String
This is because the Panda.get("/videos/#(self.panda_video_id}/encodings.json") call returns an array in the new Panda 1.0.0 gem.
I also tried :
JSON.parse(Panda.get("/videos/#{self.panda_video_id}/encodings.json").to_s)
This returns:
705: unexpected token at 'created_at2010/07/19 20:28:13 +0000video_id4df3be7b6c6888ae86f7756c77c92d8bupdated_at2010/07/19 20:28:30 +0000started_encoding_at2010/07/19 20:28:21 +0000id6e2b35ad7d1ad9c9368b473b8acd0abcextname.mp4encoding_time0encoding_progress100file_size513300height110statussuccesswidth200profile_idf1eb0fe2406d3fa3530eb7324f410789'
Question
How would you turn the call at the top so that it returns a string?
does the following work:
panda_data = Panda.get("/videos/#{self.panda_video_id}/encodings.json")
JSON.parse(panda_data.to_s)
if it doesn't what is the error output?
If panda_data is an array, panda_data.to_s is guaranteed to return a string
Not that anyone had a chance at this, but
Panda_Gem since -v=0.6 has made all Panda.[get, post, etc.] requests return a hash. So you don't need the JSON.parse anymore. Removing the JSON.parse allows it to work.

Resources