json-data-handling
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJSON Data Handling
JSON数据处理
Working effectively with JSON data structures.
高效处理JSON数据结构。
Python
Python
Basic Operations
基础操作
python
import jsonpython
import jsonParse JSON string
Parse JSON string
data = json.loads('{"name": "John", "age": 30}')
data = json.loads('{"name": "John", "age": 30}')
Convert to JSON string
Convert to JSON string
json_str = json.dumps(data)
json_str = json.dumps(data)
Pretty print
Pretty print
json_str = json.dumps(data, indent=2)
json_str = json.dumps(data, indent=2)
Read from file
Read from file
with open('data.json', 'r') as f:
data = json.load(f)
with open('data.json', 'r') as f:
data = json.load(f)
Write to file
Write to file
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
undefinedwith open('output.json', 'w') as f:
json.dump(data, f, indent=2)
undefinedAdvanced
高级操作
python
undefinedpython
undefinedCustom encoder for datetime
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)
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
Handle None values
json.dumps(data, skipkeys=True)
json.dumps(data, skipkeys=True)
Sort keys
Sort keys
json.dumps(data, sort_keys=True)
undefinedjson.dumps(data, sort_keys=True)
undefinedJavaScript
JavaScript
Basic Operations
基础操作
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));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));Advanced
高级操作
javascript
// 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());javascript
// 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());Common Patterns
常见模式
Validation
数据校验
python
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number", "minimum": 0}
},
"required": ["name", "age"]
}python
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number", "minimum": 0}
},
"required": ["name", "age"]
}Validate
Validate
validate(instance=data, schema=schema)
undefinedvalidate(instance=data, schema=schema)
undefinedDeep Merge
深度合并
python
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 resultpython
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 resultNested Access
嵌套访问
python
undefinedpython
undefinedSafe nested access
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
def get_nested(data, *keys, default=None):
for key in keys:
try:
data = data[key]
except (KeyError, TypeError, IndexError):
return default
return data
Usage
Usage
value = get_nested(data, 'user', 'address', 'city', default='Unknown')
undefinedvalue = get_nested(data, 'user', 'address', 'city', default='Unknown')
undefinedTransform Keys
键名转换
python
undefinedpython
undefinedConvert snake_case to camelCase
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
undefineddef 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
undefinedBest Practices
最佳实践
✅ DO
✅ 推荐做法
python
undefinedpython
undefinedUse context managers for files
Use context managers for files
with open('data.json', 'r') as f:
data = json.load(f)
with open('data.json', 'r') as f:
data = json.load(f)
Handle exceptions
Handle exceptions
try:
data = json.loads(json_str)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
try:
data = json.loads(json_str)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
Validate structure
Validate structure
assert 'required_field' in data
undefinedassert 'required_field' in data
undefined❌ DON'T
❌ 不推荐做法
python
undefinedpython
undefinedDon't parse untrusted JSON without validation
Don't parse untrusted JSON without validation
data = json.loads(user_input) # Validate first!
data = json.loads(user_input) # Validate first!
Don't load huge files at once
Don't load huge files at once
Use streaming for large files
Use streaming for large files
Don't use eval() as alternative to json.loads()
Don't use eval() as alternative to json.loads()
data = eval(json_str) # NEVER DO THIS!
undefineddata = eval(json_str) # NEVER DO THIS!
undefinedStreaming Large JSON
大JSON文件流处理
python
import ijsonpython
import ijsonStream large JSON file
Stream large JSON file
with open('large_data.json', 'rb') as f:
objects = ijson.items(f, 'item')
for obj in objects:
process(obj)
undefinedwith open('large_data.json', 'rb') as f:
objects = ijson.items(f, 'item')
for obj in objects:
process(obj)
undefinedRemember
注意事项
- Always validate JSON structure
- Handle parse errors gracefully
- Use schemas for complex structures
- Stream large JSON files
- Pretty print for debugging
- 始终校验JSON结构
- 优雅处理解析错误
- 复杂结构使用Schema
- 对大JSON文件使用流处理
- 调试时使用格式化输出