Json Parse Error on parsing a hash - ruby

I am working on Ruby on Rails. I have a hash like below
{"attachment"=>"{:output_dir=>\"/home/mypath/\", :process_hash=>\"8b9d9c51\", :type=>\"pdf\", :processed_dir=>\"/513/9a1/88a\", :pdf=>\"/system/path/a3ae1194f76d737b6cfb141fa0fde17f78f2e94e.pdf\", :slides_count=>4, :meta=>{:swfs=>\"{/system/path/88a/8b9d9c51[*,0].swf,4}\", :pngs=>\"/system/path/8b9d9c51{page}.png\", :json=>\"/system/path/8b9d9c51.js\"}}"
In my code i have
JSON.parse(params[:attachment])
which throws me an error as
JSON::ParserError (757: unexpected token at '{:output_dir=>"/home/path", :process_hash=>"8b9d9c51", :type=>"pdf", :processed_dir=>"/513/9a1/88a", :pdf=>"/system/path/a3ae1194f76d737b6cfb141fa0fde17f78f2e94e.pdf", :slides_count=>4, :meta=>{:swfs=>"{/system/path/8b9d9c51[*,0].swf,4}", :pngs=>"/system/path/8b9d9c51{page}.png", :json=>"/system/path/8b9d9c51.js"}}'):
Suggest me how to resolve this.

JSON.parse parses an JSON formatted String into a Hash, not the other way around. I'm not sure what you'd like to accomplish?
If you're trying to convert a Hash into JSON (string) you could use
params[:attachment].to_json
If you're trying to convert a JSON (string) into Hash you could use
JSON.parse(params[:attachment])
However, your string doesn't look like JSON (it includes => where it should have :)
Valid JSON looks like:
{ "attachment": { "output_dir": "/home/mypath", "process_hash": "89r2432" } }

Related

Storing JSON from API which has null values

I'm trying to save null value in JSON into postgresql. When I use the following code:
resume = Resume.create!({
parsedres: {"Resume":{"xml:lang":"en","xmlns":"http://ns.hrxml.org/2006-02-28","xmlns:vos":"http://noresm.com/hr-xml/2006-02-28","ResumeId":{"IdValue":null}}}
})
I get an error:
NameError: undefined local variable or method `null' for main:Object
The issue is I get API data without "" for null and when I use JSON.parse
resume.parsedres = JSON.parse(response.body)
resume.save
It throws the
JSON::ParserError: 765: unexpected token at '<ParseResumeResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Code>Ack</Code><SubCode>Authentication/SubCode><Message>AccountID.</Message><CreditsRemaining>100</CreditsRemaining></ParseResumeResponse>'
Why does JSON.parse not interpret null?
In the first example you provided, the parsedres is not JSON but a Ruby Hash literal. Since the literal is Ruby code, you'd need to use Ruby's nil keyword instead of null:
resume = Resume.create!({
parsedres: {"Resume":{"xml:lang":"en","xmlns":"http://ns.hrxml.org/2006-02-28","xmlns:vos":"http://noresm.com/hr-xml/2006-02-28","ResumeId":{"IdValue":nil}}}
})
If you received a JSON string from the API, you should be able to parse it using the code you listed above:
require 'json'
resume = Resume.create!({
parsedres: JSON.parse('{"Resume":{"xml:lang":"en","xmlns":"http://ns.hrxml.org/2006-02-28","xmlns:vos":"http://noresm.com/hr-xml/2006-02-28","ResumeId":{"IdValue":null}}}')
})
Based on the exception being thrown, it looks like the response.body is XML data, not JSON.

Issue on parsing string at JSON.parse

In controller side i am getting params like
"{\"violation_date\":\"sdfsdf\",\"violation_time\":\"\"},{\"violation_date\":\"sdfdsf\",\"violation_time\":\"sdfsdf\"},{\"violation_date\":\"1233\",\"violation_
time\":\"\"},{\"violation_date\":\"test\",\"violation_time\":\"time\"}"
class of this is String. I am trying to parse this. Through
JSON.parse(params_gotton)
Got
JSON::ParserError (757: unexpected token at ',{"violation_date":"sdfdsf","violation_time":"sdfsdf"},{"violation_date":"1233","violation_time":""},{"violation_d
te":"test","violation_time":"time"}'):
What i am doing wrong here. Any suggestions?
It's not valid json, this will work (use []):
require 'json'
jsn = '[{"violation_date":"sdfsdf","violation_time":""},
{"violation_date":"sdfdsf","violation_time":"sdfsdf"},
{"violation_date":"1233","violation_time":""},
{"violation_date":"test","violation_time":"time"}]'
JSON.parse(jsn) # => [{"violation_date"=>"sdfsdf", "violation_time"=>""}, {"violation_date"=>"sdfdsf", "violation_time"=>"sdfsdf"}, {"violation_date"=>"1233", "violation_time"=>""}, {"violation_date"=>"test", "violation_time"=>"time"}]
To verify json string you could use: http://www.jslint.com/.
And basic json structure: http://json.org/
UPDATED
In your case just try this:
JSON.parse('[' + params_gotton + ']')
well, received string does not contain a proper Json structure..
First convert that received param in a proper json structure and then parse it using "JSON.parse(params_gotton)".
In above received data all key and value shud be in a key value pair string format.. remove "\" symbol from received data..
it will definitely work fine..

Cannot convert Hash to String?

I am trying to parse the JSON response from Wordnik's API. This is built with Sinatra. I keep getting the error "TypeError at /word" "can't convert Hash into String". Am I using the json parser incorrectly?
Here's my code:
get '/word' do
resp = Wordnik.words.get_random_word(:hasDictionaryDef => 'true', :maxCorpusCount => 20, :minLength => 10)
result = JSON.parse(resp)
word = result.word
return word.to_s
end
You are probably getting a hash. To convert it use to_json:
JSON.parse(resp.to_json)
You have not given what's the JSON response that you are parsing. But assuming it is something of the form
{
"word":"my_word"
}
you need to do result["word"] to get the value after parsing the JSON response.

Trying to extract key value from parsed JSON in ruby

I’m trying to parse some JSON from the twitter API and extract the value of a key (“media_url”), which is a sub-key of the key (“entities”)
so far I have:
url = 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&screen_name=print_broadcast&count=1'
response = RestClient.get(url)
data=response.body
result = JSON.parse(data)
How would I extract a key value from the parsed JSON?
I’ve tried
result[“entities”]
etc, but I get en error when trying to convert a string to integer... the result of my parsed JSON is an array - shouldn't this be a hash?
Sorry for the dumb questions.
Any help would be appreciated.
The JSON output is actually a list. Granted, it only has one element, but it's still a list.
First get result[0], then you can access ['entries'].

Hash from String in Ruby: Marshal.load? (re-create the params hash from a Rails production.log)

I want to parse Rails production.log files and recreate the params Hash. I am stuck with the Marshal.load method, which actually expects the data to be marshalled. Well, the data is well-formed but it is a String and not in a Marshal expected format.
here is the String that i regexed out of the request from the logfile:
{
"location"=>{"city"=>"München \"foo \" bar", "id"=>"462", "youtube_tags"=>""},
"authenticity_token"=>"UHi0GCNDBPN/Ms+0bqEOl4HGvUjDRw8tNvtqVl3v0dY=",
"utf8"=>"\342\234\223", "textinput"=>""
}
I tried my way around this issue with
o=JSON.parse.gsub("=>",":"))
in which case i get problems with umlauts.
Is there no way to parse or load a Hash representation from a String to actual Ruby Hash structures with Ruby 1.8.7?
This probably isn't the best way to do it, but ...
h = eval '{
"location"=>{"city"=>"München", "id"=>"462", "youtube_tags"=>""},
"authenticity_token"=>"UHi0GCNDBPN/Ms+0bqEOl4HGvUjDRw8tNvtqVl3v0dY=",
"utf8"=>"\342\234\223", "textinput"=>""
}'

Resources