Handle json in ruby - ruby

In ruby how to convert the follwing into valid json
"{\"transferType\"=>\"D\", \"accountNumber\"=>\"123\", \"employeeId\"=>\"12\", \"districtNumber\"=>\"15\", \"orderedBy\"=>\"vbcb\", \"department\"=>\"vghghj\", \"po\"=>\"23434\", \"Phone\"=>\"4542433435\", \"Instructions\"=>\"vbvcnvbnb\"}"
The class of above is string. Because Without proper Json conversion i am problem like
Javascript replace for equal symbol

First of all you should make this in to proper JSON format. So replace the => in to :
and then try JSON.load or JSON.parse will work successfully.
2.2.3 :015 > data
=> "{\"transferType\"=>\"D\", \"accountNumber\"=>\"123\", \"employeeId\"=>\"12\", \"districtNumber\"=>\"15\", \"orderedBy\"=>\"vbcb\", \"department\"=>\"vghghj\", \"po\"=>\"23434\", \"Phone\"=>\"4542433435\", \"Instructions\"=>\"vbvcnvbnb\"}"
2.2.3 :016 > JSON.parse(data.gsub("=>", ":"))
=> {"transferType"=>"D", "accountNumber"=>"123", "employeeId"=>"12", "districtNumber"=>"15", "orderedBy"=>"vbcb", "department"=>"vghghj", "po"=>"23434", "Phone"=>"4542433435", "Instructions"=>"vbvcnvbnb"}
from the result you can do anything what do you want :)

Related

Ruby Command not return expected value

In my redhat 5 RoR, i have a command calling a jar to pull xml from another system.
irb:
2.1.5 :005 > %x(java -jar ./GENTESTResult.jar -action=status -user="tester" -password="tester" -job_id="12324")
<?xml version="1.0"?><cliout action="status" request_id="1446456310693_54" >
<action_status>ERROR</action_status>
<action_status_detail>Given job not found.</action_status_detail><job id="12324"/>
</cliout>
=> ""
2.1.5 :006 > %x(java -jar ./GENTESTResult.jar -action=status -user="tester" -password="tester" -job_id="5192782")
=> "<?xml version=\"1.0\"?><cliout action=\"status\" request_id=\"1446456368168_11\" >\n<action_status>SUCCESS</action_status><action_status_detail>Job has been processed successfully.</action_status_detail><job id=\"5192782\" status=\"Failed\" >\n...(stop paste)
the first job id "12324" is not exist. the second job id 5192782 is a valid id.
I don't have question on the job 5192782.
But for job "12324", my ruby code
#lines = %x(java -jar ./GENTESTResult.jar -action=status -user="tester" -password="tester" -job_id="12324")
gave me empty string. but i really need the xml that from the result key part which is
<?xml version="1.0"?><cliout action="status" request_id="1446456310693_54" >
<action_status>ERROR</action_status>
<action_status_detail>Given job not found.</action_status_detail><job id="12324"/>
</cliout>
How can i get the string? Thank you in advance.
You are not catching the output because it's being printed on stderr.
http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html is a comprehensive blog post about the subject, you might want to look at popen3 and popen2e in particular

Open remote URL returns empty string?

I was using the following code snippet, which was working, to fetch the JSON response from the Spotify oEmbed API.
I was doing this:
response = JSON.parse(open("https://embed.spotify.com/oembed/?url=http://open.spotify.com/album/5Mxj65mCzxUjDkoqz7JXPJ").read)
But now, this stopped working because:
2.0.0p247 :017 > open("https://embed.spotify.com/oembed/?url=http://open.spotify.com/album/5Mxj65mCzxUjDkoqz7JXPJ").read
=> ""
But, using cURL, I get:
$curl https://embed.spotify.com/oembed/\?url\=http://open.spotify.com/album/5Mxj65mCzxUjDkoqz7JXPJ
{"provider_url":"https:\/\/www.spotify.com","version":"1.0","thumbnail_width":300,"height":380,"thumbnail_height":300,"title":"Illum Sphere - 13. Embryonic","width":300,"thumbnail_url":"https:\/\/d3rt1990lpmkn.cloudfront.net\/cover\/d4f5d8624752eeae3dc8bc3d58e2155d095181c1","provider_name":"Spotify","type":"rich","html":"<iframe src=\"https:\/\/embed.spotify.com\/?uri=spotify:album:5Mxj65mCzxUjDkoqz7JXPJ\" width=\"300\" height=\"380\" frameborder=\"0\" allowtransparency=\"true\"><\/iframe>"}
Any advice?
Try passing the User-Agent:
require 'open-uri'
puts open("https://embed.spotify.com/oembed/?url=http://open.spotify.com/album/5Mxj65mCzxUjDkoqz7JXPJ", "User-Agent" => "Ruby/#{RUBY_VERSION}").read
Result:
{"provider_url":"https:\/\/www.spotify.com","version":"1.0","thumbnail_width":300,"height":380,"thumbnail_height":300,"title":"
Illum Sphere - 13. Embryonic","width":300,"thumbnail_url":"https:\/\/d3rt1990lpmkn.cloudfront.net\/cover\/d4f5d8624752eeae3dc8b
c3d58e2155d095181c1","provider_name":"Spotify","type":"rich","html":"<iframe src=\"https:\/\/embed.spotify.com\/?uri=spotify:al
bum:5Mxj65mCzxUjDkoqz7JXPJ\" width=\"300\" height=\"380\" frameborder=\"0\" allowtransparency=\"true\"><\/iframe>"}

should.kind_of?(model) error with expect syntax in RSpec

I had this:
builder.class.should.kind_of?(MyCustomFormBuilder)
which I changed to
expect(builder.class).to be kind_of?(MyCustomFormBuilder)
but I get
expected #<FalseClass:0> => false
got #<Class:25336780> => MyCustomFormBuilder
How can I do this comparison with expect?
Switching from
builder.class.should.kind_of?(MyCustomFormBuilder)
to this format
expect(builder).to be_kind_of(MyCustomFormBuilder)
worked.
Note:
just builder, not builder.class
be_kind_of, not kind_of?

I always get an UndefinedConversionError in Ruby 2.0 while scraping with Mechanize

When I try to submit a textarea with Mechanize and Ruby 2.0, I always get an
Encoding::UndefinedConversionError: U+0151 from UTF-8 to ISO-8859-1
Then I tryied to convert the text with Iconv, I got a similar result:
Iconv.iconv("LATIN1", "UTF-8", text)
I get this error message:
Iconv::IllegalSequence: "őzködik, melyet "...
As the text contains east-european characters. What can I do to avoid this kind of inconveniences or how can I convert properly between different encodings?
I have found an elegant solution:
replacements = [["À", "À"], ["Á", "Á"], ["Â", "Â"], ["Ã", "Ã"], ["Ä", "Ä"], ["Å", "Å"], ["Æ", "Æ"], ["Ç", "Ç"], ["È", "È"], ["É", "É"], ["Ê", "Ê"], ["Ë", "Ë"], ["Ì", "Ì"], ["Í", "Í"], ["Î", "Î"], ["Ï", "Ï"], ["Ð", "Ð"], ["Ñ", "Ñ"], ["Ò", "Ò"], ["Ó", "Ó"], ["Ô", "Ô"], ["Õ", "Õ"], ["Ö", "Ö"], ["Ø", "Ø"], ["Ù", "Ù"], ["Ú", "Ú"], ["Û", "Û"], ["Ü", "Ü"], ["Ý", "Ý"], ["Þ", "Þ"], ["ß", "ß"], ["à", "à"], ["á", "á"], ["â", "â"], ["ã", "ã"], ["ä", "ä"], ["å", "å"], ["æ", "æ"], ["ç", "ç"], ["è", "è"], ["é", "é"], ["ê", "ê"], ["ë", "ë"], ["ì", "ì"], ["í", "í"], ["î", "î"], ["ï", "ï"], ["ð", "ð"], ["ñ", "ñ"], ["ò", "ò"], ["ó", "ó"], ["ô", "ô"], ["õ", "õ"], ["ö", "ö"], ["ø", "ø"], ["ù", "ù"], ["ú", "ú"], ["û", "û"], ["ü", "ü"], ["ý", "ý"], ["þ", "þ"], ["ÿ", "ÿ"]]
def replace(str,replacements)
replacements.each {|replacement| str.gsub!(replacement[0], replacement[1])}
return str
end
my_string=replace(my_string,replacements)

Parse string to JSON/Hash

I'm trying to convert the following string to either a hash or json.
How do I do this in ruby?
[{"place":null,"coordinates":null,"in_reply_to_user_id":null,"in_reply_to_status_id":null,
"favorited":false,"truncated":false,"created_at":"Wed Nov 16 08:00:46 +0000 2011","retweet_count":0,"in_reply_to_screen_name":null,
"user":{"profile_background_image_url":"http:\/\/a1.twimg.com\/profile_background_images\/190989640\/afcx.jpg","protected":false,
"statuses_count":23414,"profile_link_color":"FF0000"},"retweeted":false,"in_reply_to_status_id_str":null,"in_reply_to_user_id_str":null,"contributors":null,"geo":null}]
I'm running ruby1.8.7.
What you have appears to be JSON already, so I assume you're looking to get a Ruby Hash from it. If so, then this should work:
Get a JSON library, I used gem install json_pure, which is a native Ruby implementation (there's a faster, C-based version but you wouldn't notice the difference unless your JSON strings are very large or you have a lot of them).
then
require 'json'
arr = JSON(your_json_string_here)
Note that the string you gave is a single-element array containing something that will map to a Ruby Hash. If you just want the hash:
the_hash = arr[0] # or maybe arr.first
I get this:
{"coordinates"=>nil, "created_at"=>"Wed Nov 16 08:00:46 +0000 2011",
"truncated"=>false, "favorited"=>false, "in_reply_to_user_id_str"=>nil,
"contributors"=>nil, in_reply_to_status_id_str"=>nil, "retweet_count"=>0,
"geo"=>nil, "retweeted"=>false, "in_reply_to_user_id"=>nil,
"user"=>{"profile_link_color"=>"FF0000", "protected"=>false,
"statuses_count"=>23414,
"profile_background_image_url"=>"http://a1.twimg.com/profile_background_images/190989640/afcx.jpg"},
"in_reply_to_screen_name"=>nil, place"=>nil, "in_reply_to_status_id"=>nil}

Resources