Skill站外收录 @skilllib/skill-2014279369542283266
python-json-parsing
提供高效、安全、可扩展的 JSON 数据处理能力,涵盖高性能解析库选型、超大文件流式处理、注入防护、复杂结构查询及自定义类型序列化,适用于 API 集成、大数据管道和高并发服务场景。
软件开发 AI 技能
Skills.MD
# Python JSON Parsing Best Practices
Comprehensive guide to JSON parsing in Python with focus on performance, security, and scalability.
## Quick Start
### Basic JSON Parsing
```python
import json
# Parse JSON string
data = json.loads('{"name": "Alice", "age": 30}')
# Parse JSON file
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
# Write JSON file
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
```
**Key Rule:** Always specify `encoding="utf-8"` when reading/writing files.
## When to Use This Skill
Use this skill when:
- Working with JSON APIs or data interchange
- Optimizing JSON performance in high-throughput applications
- Handling large JSON files (> 100MB)
- Securing applications against JSON injection
- Extracting data from complex nested JSON structures
## Performance: Choose the Right Library
### Library Comparison (10,000 records benchmark)
| Library | Serialize (s) | Deserialize (s) | Best For |
|---------|---------------|-----------------|----------|
| **orjson** | 0.42 | 1.27 | FastAPI, web APIs (3.9x faster) |
| **msgspec** | 0.49 | 0.93 | Maximum performance (1.7x faster deserialization) |
| **json** (stdlib) | 1.62 | 1.62 | Universal compatibility |
| **ujson** | 1.41 | 1.85 | Drop-in replacement (2x faster) |
**Recommendation:**
- Use **orjson** for FastAPI/web APIs (native support, fastest serialization)
- Use **msgspec** for data pipelines (fastest overall, typed validation)
- Use **json** when compatibility is critical
### Installation
```bash
# High-performance libraries
pip install orjson msgspec ujson
# Advanced querying
pip install jsonpath-ng jmespath
# Streaming large files
pip install ijson
# Schema validation
pip install jsonschema
```
## Large Files: Streaming Strategies
For files > 100MB, avoid loading into memory.
### Strategy 1: JSONL (JSON Lines)
Convert large JSON arrays to line-delimited format:
```python
# Stream process JSONL
with open("large.jsonl", "r") as infile, open("output.jsonl", "w") as outfile:
for line in infile:
obj = json.loads(line)
obj["processed"] = True
outfile.write(json.dumps(obj) + "\n")
```
### Strategy 2: Streaming with ijson
```python
import ijson
# Process large JSON without loading into memory
with open("huge.json", "rb") as f:
for item in ijson.items(f, "products.item"):
process(item) # Handle one item at a time
```
See: `patterns/streaming-large-json.md`
## Security: Prevent JSON Injection
**Critical Rules:**
1. Always use `json.loads()`, never `eval()`
2. Validate input with `jsonschema`
3. Sanitize user input before serialization
4. Escape special characters (`"` and `\`)
**Vulnerable Code:**
```python
# NEVER DO THIS
username = request.GET['username'] # User input: admin", "role": "admin
json_string = f'{{"user":"{username}","role":"user"}}'
# Result: privilege escalation
```
**Secure Code:**
```python
# Use json.dumps for serialization
data = {"user": username, "role": "user"}
json_string = json.dumps(data) # Properly escaped
```
See: `anti-patterns/security-json-injection.md`, `anti-patterns/eval-usage.md`
## Advanced: JSONPath for Complex Queries
Extract data from nested JSON without complex loops:
```python
import jsonpath_ng as jp
data = {
"products": [
{"name": "Apple", "price": 12.88},
{"name": "Peach", "price": 27.25}
]
}
# Filter by price
query = jp.parse("products[?price>20].name")
results = [match.value for match in query.find(data)]
# Output: ["Peach"]
```
**Key Operators:**
- `$` - Root selector
- `..` - Recursive descendant
- `*` - Wildcard
- `[?<predicate>]` - Filter (e.g., `[?price > 20]`)
- `[start:end:step]` - Array slicing
See: `patterns/jsonpath-querying.md`
## Custom Objects: Serialization
Handle datetime, UUID, Decimal, and custom classes:
```python
from datetime import datetime
import json
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, set):
return list(obj)
return super().default(obj)
# Usage
data = {"timestamp": datetime.now(), "tags": {"python", "json"}}
json_str = json.dumps(data, cls=CustomEncoder)
```
See: `patterns/custom-object-serialization.md`
## Performance Checklist
- [ ] Use orjson/msgspec for high-throughput applications
- [ ] Specify UTF-8 encoding when reading/writing files
- [ ] Use streaming (ijson/JSONL) for files > 100MB
- [ ] Minify JSON for production (`separators=(',', ':')`)
- [ ] Pretty-print for development (`indent=2`)
## Security Checklist
- [ ] Never use `eval()` for JSON parsing
- [ ] Validate input with `jsonschema`
- [ ] Sanitize user input before serialization
- [ ] Use `json.dumps()` to prevent injection
- [ ] Escape special characters in user data
## Reference Documentation
**Performance:**
- `reference/python-json-parsing-best-practices-2025.md` - Comprehensive research with benchmarks
**Patterns:**
- `patterns/streaming-large-json.md` - ijson and JSONL strategies
- `patterns/custom-object-serialization.md` - Handle datetime, UUID, custom classes
- `patterns/jsonpath-querying.md` - Advanced nested data extraction
**Security:**
- `anti-patterns/security-json-injection.md` - Prevent injection attacks
- `anti-patterns/eval-usage.md` - Why never to use eval()
**Examples:**
- `examples/high-performance-parsing.py` - orjson and msgspec code
- `examples/large-file-streaming.py` - Streaming with ijson
- `examples/secure-validation.py` - jsonschema validation
**Tools:**
- `tools/json-performance-benchmark.py` - Benchmark different libraries
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「python-json-parsing」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次