JSON serialization converts objects to JSON strings, and deserialization converts them back. Every language handles this differently.
JavaScript / TypeScript
// Serialize
const json = JSON.stringify({ name: "Alice", age: 30 }, null, 2);
// Deserialize
const obj = JSON.parse(json);
// Custom serialization with replacer
const json2 = JSON.stringify(obj, (key, value) => {
if (value instanceof Date) return value.toISOString();
return value;
});
// Reviver for deserialization
const obj2 = JSON.parse(json2, (key, value) => {
if (key.endsWith('Date')) return new Date(value);
return value;
});
Limitations: No support for undefined, functions, Dates, Map, Set, or circular references.
Python
import json
from datetime import datetime
# Serialize
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data, indent=2)
# Deserialize
obj = json.loads(json_str)
# Custom encoder for dates
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json_str = json.dumps({"created": datetime.now()}, cls=DateEncoder)
Go
import "encoding/json"type User struct {
Name string json:"name"
Age int json:"age"
}
// Serialize
user := User{Name: "Alice", Age: 30}
bytes, _ := json.Marshal(user)
// Deserialize
var result User
json.Unmarshal(bytes, &result)
Java
import com.fasterxml.jackson.databind.ObjectMapper;ObjectMapper mapper = new ObjectMapper();
// Serialize
String json = mapper.writeValueAsString(user);
// Deserialize
User user = mapper.readValue(json, User.class);
Common Pitfalls
JSON.stringify loses precision for large numbersFormat your serialized output with our JSON Formatter for readability.