Python JSON
UTF-8 JSON file I/O utilities to avoid Windows encoding issues (CP-1252 vs UTF-8)
Best use case
Python JSON is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
UTF-8 JSON file I/O utilities to avoid Windows encoding issues (CP-1252 vs UTF-8)
Teams using Python JSON should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/PythonJson/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How Python JSON Compares
| Feature / Agent | Python JSON | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
UTF-8 JSON file I/O utilities to avoid Windows encoding issues (CP-1252 vs UTF-8)
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
SKILL.md Source
# Python JSON
Python on Windows defaults to the system encoding (usually CP-1252) when opening files, not UTF-8. This causes mojibake when reading JSON files containing non-ASCII characters like `£`, `€`, or accented letters.
## Instructions
When helping users with JSON file operations in Python, follow these guidelines:
1. **Never use raw file operations for JSON**: Always use a utility module that abstracts the encoding issue
2. **Always specify UTF-8 encoding**: When opening files for JSON, use `encoding='utf-8'` explicitly
3. **Use ensure_ascii=False when writing**: This preserves Unicode characters instead of escaping them to `\uXXXX`
4. **Create a json_io utility module**: For any project that reads/writes JSON files, create a dedicated utility
5. **RFC 8259 compliance**: JSON text must be encoded in UTF-8 per the JSON specification
## Examples
### Example 1: Project needs JSON file operations
```
User: Help me read and write JSON files in my Python project
Claude: I'll create a json_io utility module to abstract the Windows encoding issue:
- Create utils/json_io.py with load_json and save_json functions
- Both functions explicitly use UTF-8 encoding
- save_json uses ensure_ascii=False to preserve Unicode
[Provides implementation using the json_io pattern from reference material below]
```
### Example 2: Mojibake in JSON data
```
User: My JSON file shows £ as £ when I read it
Claude: This is the UTF-8 double-encoding bug on Windows. The £ character (U+00A3, bytes C2 A3 in UTF-8) is being read as CP-1252, where those bytes represent £.
Solution: Use explicit UTF-8 encoding when opening files:
- with open(path, 'r', encoding='utf-8') as f
I'll create a json_io utility module to prevent this issue project-wide.
[Provides implementation using the json_io pattern from reference material below]
```
### Example 3: Writing JSON with special characters
```
User: When I save JSON, my £ symbols become \u00a3
Claude: Python's json.dump() defaults to ensure_ascii=True, which escapes non-ASCII characters. To preserve them:
- Use ensure_ascii=False in json.dump()
- Always specify encoding='utf-8' when opening the file
[Provides implementation using the json_io pattern from reference material below]
```
---
# Reference Implementation Details
The sections below contain proven working code that the examples above reference.
**Reference Files in This Folder**:
- `json_io.py` - Complete UTF-8 JSON I/O utility (copy to utils/)
## json_io Pattern
**Purpose**: Abstract JSON file operations to always use UTF-8 encoding
### Code Example
```python
"""
JSON file I/O utilities with proper UTF-8 encoding.
This module abstracts JSON file operations to handle the well-known
issue of Python defaulting to system encoding on Windows instead of
UTF-8 (which is the default encoding per RFC 8259).
"""
import json
from pathlib import Path
from typing import Any, Union
def load_json(path: Union[str, Path]) -> Any:
"""
Load JSON from a file with proper UTF-8 encoding.
Args:
path: Path to the JSON file
Returns:
Parsed JSON data
"""
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
def save_json(path: Union[str, Path], data: Any, indent: int = 2) -> None:
"""
Save data to a JSON file with proper UTF-8 encoding.
Args:
path: Path to the JSON file
data: Data to serialize
indent: Indentation level (default: 2)
"""
with open(path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=indent, ensure_ascii=False)
```
**Key Points**:
- Always use `encoding='utf-8'` when opening files
- Use `ensure_ascii=False` to preserve Unicode characters in output
- Accept both str and Path objects for flexibility
- Default indent of 2 for human-readable output
## Usage Pattern
```python
from utils.json_io import load_json, save_json
# Reading
data = load_json('config.json')
# Writing
save_json('output.json', {'price': '£99.99'})
```
## The Problem Explained
### Windows Default Encoding
Python's `open()` function uses `locale.getencoding()` to determine the default encoding. On Windows, this is typically CP-1252 (Windows-1252), not UTF-8.
### The Double-Encoding Bug
When a UTF-8 file is read with CP-1252 encoding:
| Character | UTF-8 bytes | CP-1252 interpretation |
|-----------|-------------|----------------------|
| £ (U+00A3) | C2 A3 | £ |
| € (U+20AC) | E2 82 AC | € |
| é (U+00E9) | C3 A9 | é |
### RFC 8259 Requirement
Per RFC 8259 (The JSON Data Interchange Format):
> JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8.
## Troubleshooting
### Mojibake Characters
**Symptom**: Characters like `£`, `€`, `é` appear in your data
**Cause**: UTF-8 file read with CP-1252 encoding
**Solution**: Use the json_io utility module or add `encoding='utf-8'` to file open calls
### \uXXXX Escapes in Output
**Symptom**: Non-ASCII characters appear as `\u00a3` in JSON output
**Cause**: `json.dump()` default `ensure_ascii=True`
**Solution**: Use `ensure_ascii=False` in json.dump()
## Best Practices Summary
1. Create a `utils/json_io.py` module in every Python project that handles JSON files
2. Never use raw `json.load(open(...))` without explicit UTF-8 encoding
3. Use `ensure_ascii=False` when writing JSON to preserve readability
4. Consider setting `PYTHONUTF8=1` environment variable for system-wide UTF-8 default (Python 3.7+)Related Skills
adf-json-example
Fetch raw ADF JSON data from a Confluence page URL. Use this skill when you need to see real-world ADF examples, understand how Confluence represents specific elements, debug ADF parsing, or create test samples.
adf-format-json-schema
Query Atlassian Document Format (ADF) JSON schema definitions to understand ADF node and mark types. Use this skill when implementing ADF dataclass nodes/marks, or when user asks about ADF structure, ADF nodes, ADF marks, or Atlassian Document Format implementation.
json-canvas
Create and edit JSON Canvas files (.canvas) with nodes, edges, groups, and connections. Use when working with .canvas files, creating visual canvases, mind maps, flowcharts, or when the user mentions Canvas files in Obsidian.
34-ndjson-storage
Status: ACTIVE
Backend Python Expert
专注于 Python 后端开发,涵盖 FastAPI、异步编程和性能优化。
Add prerequisite install script for Python deps (self-contained skill)
No description provided.
thor-skills
An entry point and router for AI agents to manage various THOR-related cybersecurity tasks, including running scans, analyzing logs, troubleshooting, and maintenance.
grail-miner
This skill assists in setting up, managing, and optimizing Grail miners on Bittensor Subnet 81, handling tasks like environment configuration, R2 storage, model checkpoint management, and performance tuning.
ux
This AI agent skill provides comprehensive guidance for creating professional and insightful User Experience (UX) designs, covering user research, information architecture, interaction design, visual guidance, and usability evaluation. It aims to produce actionable, user-centered solutions that avoid generic AI aesthetics.
modal-deployment
Run Python code in the cloud with serverless containers, GPUs, and autoscaling using Modal. This skill enables agents to generate code for deploying ML models, running batch jobs, serving APIs, and scaling compute-intensive workloads.
vly-money
Generate crypto payment links for supported tokens and networks, manage access to X402 payment-protected content, and provide direct access to the vly.money wallet interface.
astro
This skill provides essential Astro framework patterns, focusing on server-side rendering (SSR), static site generation (SSG), middleware, and TypeScript best practices. It helps AI agents implement secure authentication, manage API routes, and debug rendering behaviors within Astro projects.