json-data-handling by bobmatnyc/claude-mpm-skills
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill json-data-handling高效处理 JSON 数据结构。
import json
# 解析 JSON 字符串
data = json.loads('{"name": "John", "age": 30}')
# 转换为 JSON 字符串
json_str = json.dumps(data)
# 美化输出
json_str = json.dumps(data, indent=2)
# 从文件读取
with open('data.json', 'r') as f:
data = json.load(f)
# 写入文件
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
# 自定义日期时间编码器
from datetime import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json_str = json.dumps({'date': datetime.now()}, cls=DateTimeEncoder)
# 处理 None 值
json.dumps(data, skipkeys=True)
# 键排序
json.dumps(data, sort_keys=True)
// 解析 JSON 字符串
const data = JSON.parse('{"name": "John", "age": 30}');
// 转换为 JSON 字符串
const jsonStr = JSON.stringify(data);
// 美化输出
const jsonStr = JSON.stringify(data, null, 2);
// 从文件读取 (Node.js)
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
// 写入文件
fs.writeFileSync('output.json', JSON.stringify(data, null, 2));
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
// 自定义替换器
const jsonStr = JSON.stringify(data, (key, value) => {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
});
// 过滤属性
const filtered = JSON.stringify(data, ['name', 'age']);
// 处理循环引用
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return;
seen.add(value);
}
return value;
};
};
JSON.stringify(circularObj, getCircularReplacer());
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number", "minimum": 0}
},
"required": ["name", "age"]
}
# 验证
validate(instance=data, schema=schema)
def deep_merge(dict1, dict2):
result = dict1.copy()
for key, value in dict2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
# 安全的嵌套访问
def get_nested(data, *keys, default=None):
for key in keys:
try:
data = data[key]
except (KeyError, TypeError, IndexError):
return default
return data
# 使用示例
value = get_nested(data, 'user', 'address', 'city', default='Unknown')
# 将 snake_case 转换为 camelCase
def to_camel_case(snake_str):
components = snake_str.split('_')
return components[0] + ''.join(x.title() for x in components[1:])
def transform_keys(obj):
if isinstance(obj, dict):
return {to_camel_case(k): transform_keys(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [transform_keys(item) for item in obj]
return obj
# 对文件使用上下文管理器
with open('data.json', 'r') as f:
data = json.load(f)
# 处理异常
try:
data = json.loads(json_str)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
# 验证结构
assert 'required_field' in data
# 不要在没有验证的情况下解析不可信的 JSON
data = json.loads(user_input) # 先验证!
# 不要一次性加载大文件
# 对于大文件请使用流式处理
# 不要使用 eval() 作为 json.loads() 的替代品
data = eval(json_str) # 绝对不要这样做!
import ijson
# 流式处理大型 JSON 文件
with open('large_data.json', 'rb') as f:
objects = ijson.items(f, 'item')
for obj in objects:
process(obj)
每周安装量
89
代码仓库
GitHub 星标数
18
首次出现
Jan 23, 2026
安全审计
安装于
opencode70
gemini-cli69
claude-code67
codex66
github-copilot59
cursor56
Working effectively with JSON data structures.
import json
# Parse JSON string
data = json.loads('{"name": "John", "age": 30}')
# Convert to JSON string
json_str = json.dumps(data)
# Pretty print
json_str = json.dumps(data, indent=2)
# Read from file
with open('data.json', 'r') as f:
data = json.load(f)
# Write to file
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
# Custom encoder for datetime
from datetime import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json_str = json.dumps({'date': datetime.now()}, cls=DateTimeEncoder)
# Handle None values
json.dumps(data, skipkeys=True)
# Sort keys
json.dumps(data, sort_keys=True)
// Parse JSON string
const data = JSON.parse('{"name": "John", "age": 30}');
// Convert to JSON string
const jsonStr = JSON.stringify(data);
// Pretty print
const jsonStr = JSON.stringify(data, null, 2);
// Read from file (Node.js)
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
// Write to file
fs.writeFileSync('output.json', JSON.stringify(data, null, 2));
// Custom replacer
const jsonStr = JSON.stringify(data, (key, value) => {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
});
// Filter properties
const filtered = JSON.stringify(data, ['name', 'age']);
// Handle circular references
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return;
seen.add(value);
}
return value;
};
};
JSON.stringify(circularObj, getCircularReplacer());
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number", "minimum": 0}
},
"required": ["name", "age"]
}
# Validate
validate(instance=data, schema=schema)
def deep_merge(dict1, dict2):
result = dict1.copy()
for key, value in dict2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
# Safe nested access
def get_nested(data, *keys, default=None):
for key in keys:
try:
data = data[key]
except (KeyError, TypeError, IndexError):
return default
return data
# Usage
value = get_nested(data, 'user', 'address', 'city', default='Unknown')
# Convert snake_case to camelCase
def to_camel_case(snake_str):
components = snake_str.split('_')
return components[0] + ''.join(x.title() for x in components[1:])
def transform_keys(obj):
if isinstance(obj, dict):
return {to_camel_case(k): transform_keys(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [transform_keys(item) for item in obj]
return obj
# Use context managers for files
with open('data.json', 'r') as f:
data = json.load(f)
# Handle exceptions
try:
data = json.loads(json_str)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
# Validate structure
assert 'required_field' in data
# Don't parse untrusted JSON without validation
data = json.loads(user_input) # Validate first!
# Don't load huge files at once
# Use streaming for large files
# Don't use eval() as alternative to json.loads()
data = eval(json_str) # NEVER DO THIS!
import ijson
# Stream large JSON file
with open('large_data.json', 'rb') as f:
objects = ijson.items(f, 'item')
for obj in objects:
process(obj)
Weekly Installs
89
Repository
GitHub Stars
18
First Seen
Jan 23, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode70
gemini-cli69
claude-code67
codex66
github-copilot59
cursor56
Vue 3 调试指南:解决响应式、计算属性与监听器常见错误
11,800 周安装