Learn/Working with JSON

JSON Parsing & Serialization

Parsing converts a JSON string into a usable data structure. Serialization does the reverse. These are the two operations you will perform most frequently when working with JSON in any language.

Intermediate~15 min read

The Parse-Serialize Cycle

JSON Parse & Serialize Flow

Every language has built-in functions for these operations. The string form is used for storage, network transfer, and file I/O. The native object form is what you work with in code.

JavaScript

JSON.parse() — String to Object

Basic parsingjavascript
1const jsonString = '{"name":"Alice","age":30}';
2
3const user = JSON.parse(jsonString);
4
5console.log(user.name); // "Alice"
6console.log(user.age); // 30
7console.log(typeof user); // "object"

JSON.stringify() — Object to String

Serialization with formattingjavascript
1const user = {
2 name: "Alice",
3 age: 30,
4 roles: ["admin", "editor"]
5};
6
7// Compact (for APIs / storage)
8const compact = JSON.stringify(user);
9// '{"name":"Alice","age":30,"roles":["admin","editor"]}'
10
11// Pretty-printed (for debugging / config files)
12const pretty = JSON.stringify(user, null, 2);
13// {
14// "name": "Alice",
15// "age": 30,
16// "roles": ["admin", "editor"]
17// }

Error Handling (Critical)

Always wrap parse in try-catchjavascript
1function safeJsonParse(text) {
2 try {
3 return { data: JSON.parse(text), error: null };
4 } catch (err) {
5 return { data: null, error: err.message };
6 }
7}
8
9const result = safeJsonParse('{"valid": true}');
10// { data: { valid: true }, error: null }
11
12const bad = safeJsonParse('{invalid}');
13// { data: null, error: "Expected property name..." }

Never Use eval()

Never use eval(jsonString) to parse JSON. It executes arbitrary code and is a severe security vulnerability. Always use JSON.parse().

The Reviver Function

JSON.parse() accepts an optional second argument — a reviver function that transforms values during parsing:

Converting date strings to Date objectsjavascript
1const json = '{"created":"2026-03-28T12:00:00Z","name":"Task"}';
2
3const obj = JSON.parse(json, (key, value) => {
4 if (key === "created") return new Date(value);
5 return value;
6});
7
8console.log(obj.created instanceof Date); // true
9console.log(obj.created.getFullYear()); // 2026

The Replacer Function

JSON.stringify() accepts a replacer to filter or transform values:

Filtering sensitive fieldsjavascript
1const user = {
2 name: "Alice",
3 email: "[email protected]",
4 password: "secret123",
5 apiKey: "sk_live_abc..."
6};
7
8const safe = JSON.stringify(user, (key, value) => {
9 if (key === "password" || key === "apiKey") return undefined;
10 return value;
11}, 2);
12
13// { "name": "Alice", "email": "[email protected]" }

Python

Python JSON parsing and serializationpython
1import json
2
3# Parse (deserialize)
4json_string = '{"name": "Alice", "age": 30}'
5user = json.loads(json_string)
6print(user["name"]) # Alice
7
8# Serialize
9user_dict = {"name": "Alice", "age": 30, "roles": ["admin"]}
10json_output = json.dumps(user_dict, indent=2)
11print(json_output)
12
13# File I/O
14with open("data.json", "w") as f:
15 json.dump(user_dict, f, indent=2)
16
17with open("data.json", "r") as f:
18 loaded = json.load(f)

Fetch API + JSON

The most common real-world usage — fetching JSON from an API:

Fetching and parsing API datajavascript
1async function getUser(id) {
2 const response = await fetch(`/api/users/${id}`);
3
4 if (!response.ok) {
5 throw new Error(`HTTP ${response.status}`);
6 }
7
8 const user = await response.json(); // parses JSON automatically
9 return user;
10}
11
12// Sending JSON to an API
13async function createUser(data) {
14 const response = await fetch("/api/users", {
15 method: "POST",
16 headers: { "Content-Type": "application/json" },
17 body: JSON.stringify(data) // serializes to JSON
18 });
19
20 return response.json();
21}

Language Comparison

OperationJavaScriptPythonGoJava
Parse stringJSON.parse(s)json.loads(s)json.Unmarshal()new ObjectMapper().readValue()
SerializeJSON.stringify(o)json.dumps(o)json.Marshal()mapper.writeValueAsString()
Read filefs.readFileSync()json.load(f)json.NewDecoder(f)mapper.readValue(file)
Write filefs.writeFileSync()json.dump(o, f)json.NewEncoder(f)mapper.writeValue(file)
Error typeSyntaxErrorJSONDecodeErrorerrorJsonProcessingException

Try It Yourself

This JSON represents an API response. Modify it to add a new user, change the pagination, or introduce an error to see what happens when you click Run & Validate.

Try It Yourself

Simulate an API response — modify and validate

Performance Tips

Avoid double-parsing

Never JSON.parse(JSON.stringify(obj)) to clone — use structuredClone() instead.

Stream large files

Use streaming parsers for files > 50MB to avoid memory issues.

Cache parsed results

Parse config files once at startup, not on every request.

Use response.json()

The Fetch API parses JSON in an optimized path — use it instead of text + parse.

Frequently Asked Questions

What is the difference between parsing and serialization?
Parsing (deserialization) converts a JSON string into a native data structure (object, dictionary). Serialization converts a native data structure back into a JSON string.
Is JSON.parse() safe to use with untrusted input?
JSON.parse() itself is safe — it does not execute code. However, you should validate the parsed data structure before using it. Never use eval() to parse JSON.
What happens if JSON.parse() fails?
It throws a SyntaxError. Always wrap JSON.parse() in a try-catch block to handle malformed input gracefully.
How do I handle large JSON files?
For files over ~50MB, consider streaming parsers (like JSONStream in Node.js or ijson in Python) instead of loading the entire file into memory.
Does JSON.stringify() handle circular references?
No. JSON.stringify() throws a TypeError for circular references. Use a replacer function or libraries like flatted to handle circular structures.