Skip to content

Instantly share code, notes, and snippets.

@navicore
Last active April 14, 2024 20:24
Show Gist options
  • Save navicore/01af326d0a2056289b5df8bf20dfd204 to your computer and use it in GitHub Desktop.
Save navicore/01af326d0a2056289b5df8bf20dfd204 to your computer and use it in GitHub Desktop.
import json
import os
import markdownify
from datetime import datetime
# Ensure the output directory exists
output_dir = 'out'
os.makedirs(output_dir, exist_ok=True)
# Loop through all json files in the current directory
for filename in os.listdir('.'):
if filename.endswith('.json'):
with open(filename, 'r') as file:
data = json.load(file)
# Extract relevant data
title = data.get('title', 'Untitled').strip()
text_content = data.get('textContent', '').strip()
annotations = data.get('annotations', [])
attachments = data.get('attachments', [])
labels = data.get('labels', [])
created_timestamp_usec = int(data.get('createdTimestampUsec', 0))
# Format the timestamp into a readable date
date = datetime.fromtimestamp(created_timestamp_usec / 1_000_000).strftime('%Y-%m-%d')
# Convert text content from HTML to Markdown if necessary
markdown_text = markdownify.markdownify(text_content, heading_style="ATX")
# Process annotations for links and descriptions
links_markdown = ""
for annotation in annotations:
if 'url' in annotation:
link = annotation['url']
link_title = annotation.get('title', link)
links_markdown += f"[{link_title}]({link})\n\n"
# Process attachments for image links
attachments_markdown = ""
for attachment in attachments:
file_path = attachment.get('filePath', '')
if file_path:
attachments_markdown += f"![]({file_path})\n"
# Process labels
labels_markdown = ""
for label in labels:
label_name = label.get('name', '').strip()
if label_name:
labels_markdown += f"#{label_name}\n"
# Assemble the final markdown content with a YAML header
markdown_content = f"---\ntitle: {title}\ndate: {date}\n---\n\n{markdown_text}\n\n{links_markdown}{attachments_markdown}\n{labels_markdown}"
# Write the markdown content to a new file in the output directory
markdown_filename = os.path.splitext(filename)[0] + '.md'
with open(os.path.join(output_dir, markdown_filename), 'w') as markdown_file:
markdown_file.write(markdown_content)
print("Conversion completed.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment