A lightweight Python utility that converts markdown files into JSON-compatible escaped strings. Perfect for embedding markdown content as string values in JSON objects, API payloads, or database storage.
- 🔄 Clean Conversion: Converts markdown files to properly escaped JSON strings
- ⚡ Zero Dependencies: Uses Python standard library only - no external packages
- 📝 Proper Escaping: Handles all special characters (quotes, backslashes, newlines)
- 💻 CLI & Library: Use as command-line tool or import as a Python module
- 📤 Flexible Output: Print to console or save to file
- 🎯 Simple API: Single-purpose tool with straightforward interface
- Converting markdown documentation into JSON payloads for APIs
- Embedding markdown content in JSON configuration files
- Preparing markdown for database storage (MongoDB, PostgreSQL JSONB, etc.)
- Creating JSON-compatible strings from design documents
- Processing markdown for REST API requests/responses
- Python 3.6+
- No external dependencies required
- Clone or download the project
- No additional installation needed - ready to use immediately!
Basic usage (print to console):
python markdown_to_json_string.py input.mdSave to file:
python markdown_to_json_string.py input.md -o output.txtWith paths:
python markdown_to_json_string.py /path/to/document.md -o /path/to/output.txtImport and use in your own scripts:
from markdown_to_json_string import markdown_to_json_string, process_markdown_file
# Method 1: Convert markdown string directly
markdown_content = """
# My Document
This is **bold** and this is *italic*.
"""
json_string = markdown_to_json_string(markdown_content)
print(json_string)
# Method 2: Process a file
json_string = process_markdown_file('document.md')
print(json_string)Using the converted string in a JSON object:
import json
from markdown_to_json_string import process_markdown_file
# Convert markdown to JSON-safe string
description = process_markdown_file('product_description.md')
# Create JSON object
data = {
"product_id": "12345",
"name": "Widget Pro",
"description": description, # Markdown content as JSON string
"price": 99.99
}
# Serialize to JSON
json_output = json.dumps(data, indent=2)
print(json_output)Output:
{
"product_id": "12345",
"name": "Widget Pro",
"description": "# Widget Pro\n\nThe **ultimate** widget for all your needs.\n\n- Feature 1\n- Feature 2",
"price": 99.99
}The converter performs these steps:
- Reads the markdown file in UTF-8 encoding
- Escapes special characters using Python's
json.dumps():- Double quotes (
") →\" - Backslashes (
\) →\\ - Newlines (line breaks) →
\n - Tabs →
\t
- Double quotes (
- Returns the escaped string (without outer quotes)
Input markdown (input.md):
# Hello World
This is a "test" document.
## Features
- Feature 1
- Feature 2Output string:
# Hello World\n\nThis is a \"test\" document.\n\n## Features\n\n- Feature 1\n- Feature 2
This output can be safely embedded as a JSON value:
{
"content": "# Hello World\n\nThis is a \"test\" document.\n\n## Features\n\n- Feature 1\n- Feature 2"
}Converts raw markdown content to a JSON-compatible escaped string.
Parameters:
markdown_content(str): Raw markdown text to convert
Returns:
str: JSON-compatible escaped string (without outer quotes)
Example:
result = markdown_to_json_string("# Title\n\nParagraph")
print(result) # "# Title\\n\\nParagraph"Reads a markdown file and converts it to a JSON-compatible string.
Parameters:
file_path(str): Path to the markdown file
Returns:
str: JSON-compatible escaped string
Raises:
FileNotFoundError: If the file doesn't existIOError: If there's an error reading the file
Example:
try:
result = process_markdown_file('document.md')
print(result)
except FileNotFoundError:
print("File not found!")python markdown_to_json_string.py INPUT_FILE [-o OUTPUT_FILE]
| Argument | Required | Description |
|---|---|---|
INPUT_FILE |
Yes | Path to input markdown file |
-o, --output |
No | Path to output file (prints to console if omitted) |
Convert markdown documentation to JSON for an API:
from markdown_to_json_string import process_markdown_file
import json
# Convert markdown docs
api_docs = process_markdown_file('api_documentation.md')
# Create API response
response = {
"status": "success",
"documentation": api_docs,
"version": "1.0"
}
# Send as JSON
print(json.dumps(response))Store markdown content in a JSON database field:
import pymongo
from markdown_to_json_string import process_markdown_file
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['my_database']
articles = db['articles']
# Convert markdown article
content = process_markdown_file('article.md')
# Insert into MongoDB
article = {
"title": "My Article",
"author": "John Doe",
"content": content, # Markdown stored as string
"published": "2025-01-15"
}
articles.insert_one(article)Convert multiple markdown files:
import os
from markdown_to_json_string import process_markdown_file
input_dir = './markdown_files'
output_dir = './json_strings'
for filename in os.listdir(input_dir):
if filename.endswith('.md'):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename.replace('.md', '.txt'))
# Convert and save
json_string = process_markdown_file(input_path)
with open(output_path, 'w') as f:
f.write(json_string)
print(f"Converted: {filename}")Prepare markdown for a REST API request:
import requests
from markdown_to_json_string import process_markdown_file
# Convert markdown content
description = process_markdown_file('product_description.md')
# Send to API
payload = {
"product": {
"name": "New Product",
"description": description
}
}
response = requests.post(
'https://api.example.com/products',
json=payload
)
print(response.json())The script properly escapes these special characters:
| Character | Escaped Form | Purpose |
|---|---|---|
" (quote) |
\" |
Prevents breaking JSON strings |
\ (backslash) |
\\ |
Prevents escape sequence issues |
\n (newline) |
\n |
Preserves line breaks as escape sequence |
\t (tab) |
\t |
Preserves tabs as escape sequence |
\r (carriage return) |
\r |
Handles Windows line endings |
Solution: Check that the input file path is correct and the file exists
ls -la path/to/file.mdSolution: Ensure your markdown file is UTF-8 encoded
file -I input.mdConvert to UTF-8 if needed:
iconv -f ISO-8859-1 -t UTF-8 input.md > input_utf8.mdSolution: The output is correct, but terminals display escape sequences. Save to file to see the raw string:
python markdown_to_json_string.py input.md -o output.txt
cat output.txtSolution: Check write permissions for output directory
chmod +w output_directory/Verify the conversion works correctly:
from markdown_to_json_string import markdown_to_json_string
import json
# Test input
test_markdown = '''# Test
This is a "test" with special characters: \\ and newlines.'''
# Convert
result = markdown_to_json_string(test_markdown)
# Verify it's valid JSON when embedded
test_json = json.dumps({"content": result})
parsed = json.loads(test_json)
assert parsed["content"] == test_markdown
print("✅ Conversion test passed!")- Speed: Processes ~1MB of markdown in <0.1 seconds
- Memory: Loads entire file into memory - suitable for files up to 100MB
- Efficiency: Single-pass conversion with no temporary files
- Loads entire file into memory (not suitable for multi-GB files)
- Assumes UTF-8 encoding (non-UTF-8 files must be converted first)
- Does not validate markdown syntax
- Does not render markdown to HTML
If you need different functionality:
- Markdown to HTML: Use
markdownormistunelibrary - Markdown parsing: Use
markdown-it-pyorcommonmark - JSON schema validation: Use
jsonschemalibrary
MIT
Perfect for: API developers, backend engineers, data engineers, anyone needing to embed markdown content in JSON payloads or databases.