mcpField
J
json-data-handling

json-data-handling

github.com/bobmatnyc开发78389 次安装15 周前更新
代码仓库

关于 json-data-handling

json-data-handling 是介绍 JSON 数据处理的技能,适用于使用 Python 或 JavaScript 的开发者。内容涵盖解析、转换、验证、嵌套数据访问及大型文件流式处理。

主要功能

  1. 01解析与序列化 JSON
  2. 02自定义编码与转换
  3. 03使用 schema 验证
  4. 04合并对象与访问嵌套值
  5. 05流式处理大型 JSON 文件

适用场景

  1. 01验证外部 JSON 输入
  2. 02转换对象键名与数据格式
  3. 03处理大型 JSON 文件

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill json-data-handling

安装后在 Claude Code 中输入/json-data-handling确认已加载。

附带文件metadata.json

详细介绍

JSON 数据处理

高效处理 JSON 数据结构。

Python

基本操作
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)

JavaScript

基本操作
// 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!

流式处理大型 JSON

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)

请记住

  • 始终验证 JSON 结构
  • 妥善处理解析错误
  • 对于复杂结构,使用架构
  • 流式处理大型 JSON 文件
  • 使用美化输出进行调试

评论

支持 Markdown