Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Migrate Ghost json export to Markdown files for static generation
require 'json'
require 'open-uri'
class GhostMigrate
attr_accessor :archive, :posts, :tags, :posts_tags, :template, :base_url
def run(filename, url)
@archive = JSON.parse(File.read(filename))
@posts = archive["db"][0]["data"]["posts"]
@tags = archive["db"][0]["data"]["tags"]
@posts_tags = archive["db"][0]["data"]["posts_tags"]
@template = DATA.read
@base_url = url
posts.each_with_index do |p,i|
File.open("ghost-#{i}.md", "w") do |f|
f.write post(p)
end
end
end
def post(post_data)
title = post_data["title"]
uuid = post_data["uuid"]
id = post_data["id"]
permalink = post_data["slug"]
date = post_data["published_at"]#[0...10]
image = (download_image post_data["feature_image"], id) || "none"
markdown = JSON.parse(post_data["mobiledoc"])["cards"][0][1]["markdown"]
template % [id, title, permalink, date, formatted_tags(id), image, markdown]
end
def formatted_tags(post_id)
tag_ids = posts_tags.find_all { |pt| pt["post_id"] == post_id }.map { |pt| pt["tag_id"] }
selected_tags = tag_ids.inject([]) do |r,ti|
r << " - \"#{(tags.find { |t| t["id"] == ti })["name"]}\""
end
selected_tags.join("\n")
end
def download_image(url, id)
return unless url
image_url = base_url + url
image_name = File.basename url
image_output = "img/#{id}-#{image_name}"
unless File.exist?(image_output)
image_data = open(image_url, &:read)
File.open(image_output, "w") do |f|
f.write(image_data)
end
end
image_output
end
end
if __FILE__ == $0
puts "MIGRATE!"
GhostMigrate.new.run ARGV[0], ARGV[1]
end
__END__
---
id: %s
title: "%s"
permalink: %s/index.html
date: %s
tags:
%s
layout: layouts/post.njk
feature_image: %s
---
%s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment