Friday, January 31, 2014

XML to JSON

Right , so I was going to blog about the fail of a night I had last night. I tried winging the creation of an application, but turns out that it’s really not a smart idea and you become unorganized. Lesson learned!
So instead of informing you about my failures, I’m going to show you my small triumph! Holla! Today work asked me to create a ruby script that fetches RSS feeds from various news sites and create a JSON out of the RSS feeds. Figuring this has a gem out there I googled the situation. All I got in return was a bunch of gems that halfway did what I needed, or made it x10 harder than it needed to be. So I broke it down into individual steps then created the ruby to go along with it.
1.       Get response body from URL *RSSfeed
2.       Change response body from XML to JSON.
3.       Output to JSON file.

require 'net/http'
require 'active_support/all'

s=Net::HTTP.get_response(URI.parse('http://rss.cnn.com/rss/cnn_topstories.rss')).body
response = Hash.from_xml(s).to_json
    file = File.new("feed.JSON", "w")
     file.syswrite(response)
     file.close

That’s all I want , pretty simple and not that complex. Other gems were going to have me build my own template and blah blah blah. Nah , so I looked a bit into activesupport ( used this gem in previous ruby scripts I’ve created) and it helps with the .from_xml . I’ve been searching for a while on how to switch xml to json for the web app I’ve helped create here at work. But dang.. It’s just so short and sweet and it makes me excited. :D

Hope this helps if you need it

-Hannah

No comments:

Post a Comment