Storing JSON from API which has null values - ruby

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.

Related

Ruby Sinatra and JSON objects from toodledo API 2.0

I have a small problem with receiving JSON objects. I'm using Ruby 1.9.3 and my goal is to receive my tasks from an API via RestClient and print them more or less pretty onto the page.
I created a route /test:
get '/test' do
json_ip_url = "http://api.toodledo.com/2/tasks/get.php?key=198196ae24792467eec09ac2191*****;modafter=1234567890;fields=folder,star,priority"
ip_details = RestClient.get(json_ip_url)
test = JSON.pretty_generate(ip_details) # => throws exception
end
The JSON#pretty_generate line throws an error, "only generation of JSON objects or arrays allowed". What am I doing wrong here?
Update:
I'am now able to output via pretty_generate, but what do I have to do, to get the elements of it. Here is the JSON Data, it seems to me its an Array with Objects inside of it?
[{"num":"18","total":"18"},{"id":"11980343","title":"Add some items to your todo list","modified":1391670256,"completed":0,"folder":"0","star":"0"},{"id":"11980345","title":"Visit the Settings section and configure your account","modified":1391670256,"completed":0,"folder":"0","star":"0"},{"id":"11980347","title":"Watch our tutorial videos in the Help section","modified":1391670256,"completed":0,"folder":"0","star":"1"},{"id":"12607789","title":"test","modified":1392285802,"completed":0,"folder":"0","star":"0"},{"id":"12636039","title":"My Task","modified":1392308705,"completed":0,"folder":"0","star":"0"},{"id":"12636041","title":"Another","modified":1392308705,"completed":0,"folder":"0","star":"1"},{"id":"12636143","title":"My Task","modified":1392308789,"completed":0,"folder":"0","star":"0"},{"id":"12636145","title":"Another","modified":1392308789,"completed":0,"folder":"0","star":"1"},{"id":"12636449","title":"My Task","modified":1392308950,"completed":0,"folder":"0","star":"0"},{"id":"12636451","title":"Another","modified":1392308950,"completed":0,"folder":"0","star":"1"},{"id":"12636621","title":"My Task","modified":1392309061,"completed":0,"folder":"0","star":"0"},{"id":"12636623","title":"Another","modified":1392309061,"completed":0,"folder":"0","star":"1"},{"id":"12636665","title":"My Task","modified":1392309085,"completed":0,"folder":"0","star":"0"},{"id":"12636667","title":"Another","modified":1392309085,"completed":0,"folder":"0","star":"1"},{"id":"12636733","title":"My Task","modified":1392309137,"completed":0,"folder":"0","star":"0"},{"id":"12636735","title":"Another","modified":1392309137,"completed":0,"folder":"0","star":"1"},{"id":"12637135","title":"My Task","modified":1392309501,"completed":0,"folder":"0","star":"0"},{"id":"12637137","title":"Another","modified":1392309501,"completed":0,"folder":"0","star":"1"}]
The Code I used for pretty_generate:
get '/save' do
jdata = params[:data]
response = RestClient.get 'http://api.toodledo.com/2/tasks/get.php?key=da21e24e2a00ba9d45008974aed00***;modafter=1234567890;fields=folder,star,priority', {:accept => :json}
test = JSON.parse(response)
test.to_json
output = JSON.pretty_generate(test)
puts output
RestClient#get returns the raw response as a string (and not a hash or array) when called without a block, so ip_details isn't a structure that JSON#pretty_generate knows how to handle. You need to use JSON#parse to turn the response into a hash or array first.

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..

Json Parse Error on parsing a hash

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" } }

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.

How do I extract a value from a JSON response?

I am writing some tests in Ruby using RestClient. The test is working fine and the response is in JSON however when I parse the JSON and try to extract the values I am looking for I get an error saying IndexError: key not found
IMO, my code should work. The JSON is:
{"user":{"#xmlns":{"dvi":"http:\/\/xxxx","a":"http:\/\/xxxx","$":"http:\/\/xxxx"},"link":[{"#rel":"self","$":"http:\/\/xxxx"},{"#rel":"user","$":"http:\/\/xxxx"},{"#rel":"usage","$":"xxxx"},{"#rel":"repositories","$":"http:\/\/xxxx"},{"#rel":"shares","$":"http:\/\/xxxx"},{"#rel":"shareMemberships","$":"http:\/\/xxxx"}],"phone":{"$":"3518012343001"},"email":{"$":""},"firstName":{"$":"Jim"},"lastName":{"$":"Joe"},"uid":{"$":"91bc7a72bc724e5e9b53e688dd105ed4"},"accountName":{"$":"3518012343001"},"notificationMethod":{"$":"email sms"},"accountStatus":{"$":"Active"},"serviceLevel":{"$":"5"},"repositoryCount":{"$":"1"},"usage":{"allowed":{"$":"5368709120"},"total":{"$":"1024"}},"contactEmail":{"$":"jim#joe.com"}}}
and my code is:
result = jsonabove
jdoc = JSON.parse(result)
notificationMethod = jdoc.fetch("notificationMethod")
return notificationMethod
That's happening because the notificationMethod key isn't the first level key in your hash. After preparing theJSON#parse method, you have a hash with only one key called user. You should get the value by this key and then apply your notificationMethod key. It looks like this:
require 'json'
result = <<HERE
{"user":{"......"}}
HERE
jdoc = JSON.parse(result)
notificationMethod = jdoc.fetch("user").fetch("notificationMethod")
puts notificationMethod

Resources