jsondecode.com logo

HomeChevronBlogChevronJSON Serialization and Deserialization Explained

Blog post

JSON Serialization and Deserialization Explained

Understand JSON serialization and deserialization — how data transforms to JSON strings and back, with examples across languages.

author

Shashank Jain

Author

14/06/20261 minute 55 seconds read
JSON Serialization and Deserialization ExplainedJSON Serialization and Deserialization Explained

Article

What Are Serialization and Deserialization?

Serialization converts an in-memory object into a format that can be stored or transmitted — in this case, a JSON string. Deserialization is the reverse: parsing a JSON string back into an in-memory object. These are the most fundamental JSON operations in any programming language.

LanguageSerializeDeserialize
JavaScriptJSON.stringify()JSON.parse()
Pythonjson.dumps()json.loads()
Java (Jackson)mapper.writeValueAsString()mapper.readValue()
Gojson.Marshal()json.Unmarshal()
C# (.NET)JsonSerializer.Serialize()JsonSerializer.Deserialize()
PHPjson_encode()json_decode()

What Gets Lost in Serialization

JSON supports only 6 types: string, number, boolean, null, array, and object. These types are not preserved during round-trip serialization:

TypeJSON resultRestore how
Date objectISO stringreviver function / manual parsing
undefinedomitted from objects / null in arrayscheck before serializing
Functionomittedcannot serialize — use different approach
BigIntthrows TypeErrorconvert to string first
Map / Setempty object {}convert to Array/Object first
Class instanceplain object (methods lost)custom toJSON() method

Custom Serialization in JavaScript

class User {
  constructor(public name: string, public createdAt: Date) {}

  toJSON() {
    return {
      name: this.name,
      createdAt: this.createdAt.toISOString(),
    };
  }
}

const user = new User('Alice', new Date());
console.log(JSON.stringify(user));
// {"name":"Alice","createdAt":"2026-06-14T12:00:00.000Z"}

// Reviver for deserialization
const parsed = JSON.parse(jsonStr, (key, value) => {
  if (key === 'createdAt') return new Date(value);
  return value;
});

Custom Serialization in Python

import json
from datetime import datetime
from dataclasses import dataclass, asdict

@dataclass
class User:
    name: str
    created_at: datetime

class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

user = User('Alice', datetime.now())
print(json.dumps(asdict(user), cls=DateTimeEncoder))

Serialization Performance Tips

  • Avoid serializing large objects unnecessarily — be selective about what goes in the payload
  • Use streaming serializers for large datasets (instead of building the full string in memory)
  • Cache serialized strings when the object does not change frequently
  • In Python, orjson is 5-10x faster than the standard json module
  • In JavaScript, JSON.stringify is already highly optimized — prefer it over third-party alternatives

FAQ

Is JSON.stringify the same as serialization?

Yes — JSON.stringify serializes a JavaScript value to a JSON string. JSON.parse deserializes it back. The terms are interchangeable for JSON.

What is the difference between JSON and binary serialization?

JSON is human-readable text. Binary formats like Protocol Buffers, MessagePack, and CBOR are more compact and faster to parse but not human-readable. Use JSON for APIs and config; use binary for high-throughput internal services.

How do I serialize a class with private fields?

Implement a custom toJSON() method (JavaScript) or __json__() equivalent that returns only the fields you want serialized. This also lets you control naming and formatting.

What is NDJSON?

Newline-Delimited JSON — each line is a separate JSON value. Useful for streaming: the sender can write records one at a time, and the receiver can parse each line as it arrives without waiting for the full payload.

How do I serialize circular references?

JSON.stringify throws on circular references. Use the flatted library (JavaScript), or write a custom replacer that tracks seen objects and replaces circular refs with a placeholder string.

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.