Skip to content

Instantly share code, notes, and snippets.

@manton
Created May 18, 2017 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manton/03a41efd6ebb1afa4ff3c482b83d1097 to your computer and use it in GitHub Desktop.
Save manton/03a41efd6ebb1afa4ff3c482b83d1097 to your computer and use it in GitHub Desktop.
# run with: ruby jsonfeed_convert_rss.rb "http://therecord.co/xml/rss.xml"
# also make sure to "gem install simple-rss" first
require 'rubygems'
require 'simple-rss'
require 'open-uri'
require 'json'
rss_url = ARGV[0]
SimpleRSS.item_tags << :"enclosure#url"
SimpleRSS.item_tags << :"enclosure#type"
SimpleRSS.item_tags << :"enclosure#length"
rss = SimpleRSS.parse(open(rss_url))
json_feed = {
version: "https://jsonfeed.org/version/1",
title: rss.channel.title,
home_page_url: rss.channel.link,
items: []
}
for rss_item in rss.items
json_item = {
id: rss_item.link,
url: rss_item.link,
title: rss_item.title.force_encoding('UTF-8'),
date_published: rss_item.pubDate.iso8601
}
if rss_item.description.to_s.length > 0
json_item[:content_text] = CGI.unescapeHTML(rss_item.description.force_encoding('UTF-8'))
end
if rss_item.content_encoded.to_s.length > 0
json_item[:content_html] = CGI.unescapeHTML(rss_item.content_encoded.force_encoding('UTF-8'))
elsif rss_item.content.to_s.length > 0
json_item[:content_html] = CGI.unescapeHTML(rss_item.content.force_encoding('UTF-8'))
end
if rss_item.enclosure_url
json_item[:attachments] = [
{
url: rss_item.enclosure_url,
mime_type: rss_item.enclosure_type,
size_in_bytes: rss_item.enclosure_length.to_i
}
]
end
json_feed[:items] << json_item
end
puts JSON.pretty_generate(json_feed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment