COMPUTER PROGRAMMING 1 (JAVASCRIPT) • DATA I/O & JSON

JSON Parse & Stringify — I can parse JSON into objects/arrays and stringify objects into JSON in supported tasks.

Learn how JavaScript converts data between JSON text and live objects so your programs can save, send, and receive information.

Historical Context & Motivation

Before the internet became the backbone of modern applications, programs needed a simple, universal way to share data. Early formats like XML (Extensible Markup Language) were powerful but verbose — they wrapped every piece of data in heavy tags that made files bloated and hard to read. Developers wanted something lighter, something that looked like the data structures they already used in code. That desire led to the creation of JSON, which stands for JavaScript Object Notation.

JSON was not invented from scratch; it was discovered inside the JavaScript language. Douglas Crockford noticed that JavaScript's object and array literals already provided a clean, readable notation for data. He formalized the rules, gave it a name, and published a specification. Because JSON maps directly to structures that almost every programming language supports — objects (or dictionaries) and arrays (or lists) — it quickly became the dominant format for web APIs, configuration files, and data storage.

1999
JSON Concept Emerges
Douglas Crockford begins using JavaScript object literal syntax as a lightweight data interchange format, recognizing its simplicity compared to XML.
2002
json.org Launches
Crockford publishes the JSON specification at json.org, giving the format an official grammar and spreading awareness to the developer community.
2009
JSON.parse & JSON.stringify Added
ECMAScript 5 (ES5) introduces built-in JSON.parse() and JSON.stringify() methods, eliminating the need for unsafe eval() calls.
2013
ECMA-404 Standard
JSON is formally standardized as ECMA-404, cementing its role as the universal data interchange format across all major programming languages.
2020s
JSON Everywhere
JSON dominates web APIs, NoSQL databases (like MongoDB), configuration files, and even game save data. It is the most widely used data format on the internet.

The central question this lesson addresses is: How do we convert between JSON text and JavaScript objects or arrays? Understanding this conversion — called parsing (text → object) and stringifying (object → text) — is essential for any task that involves saving data, sending data to a server, or receiving data from an API.

Core Principles & Definitions

Before diving into code, you need to understand several foundational ideas. JSON may look like a JavaScript object, but it is actually just a string — plain text that follows specific formatting rules. A JavaScript object, on the other hand, is a live data structure in memory that your program can manipulate. The two are related but fundamentally different, and the methods JSON.parse() and JSON.stringify() serve as the bridge between them.

1

JSON Is Text

JSON is always a string. Even though it looks like code, it is not executable JavaScript. It uses double quotes around all keys and string values, and it cannot contain functions, undefined, or comments.
2

Parsing (Text → Object)

JSON.parse() reads a JSON string and converts it into a JavaScript object or array that you can access with dot notation or bracket notation.
3

Stringifying (Object → Text)

JSON.stringify() takes a JavaScript object or array and converts it into a JSON-formatted string, ready to be saved to a file or sent over a network.
4

Supported Data Types

JSON supports six value types: strings, numbers, booleans, null, objects (key-value pairs), and arrays. Functions, undefined, Symbol, and Date objects are not natively supported.
5

Round-Tripping

When you stringify an object and then parse the result, you should get back an equivalent object. This process is called round-tripping and it only works perfectly when the data contains only JSON-safe types.
✦ KEY TAKEAWAY
Think of JSON like a shipping label on a package. The label (JSON string) describes what is inside using a standard format that any postal service (any programming language) can read. JSON.parse() is like opening the package and taking out the actual items (JavaScript objects). JSON.stringify() is like boxing up your items and writing a new label so the package can be shipped to someone else.

Visual Explanation — The Parse & Stringify Pipeline

The left box shows a JSON string — notice the double quotes around every key. The right box shows the equivalent JavaScript object in memory, where keys do not require quotes. The cyan arrow represents JSON.parse() and the pink arrow represents JSON.stringify().

The diagram above captures the entire core idea of this lesson. On the left, you see a JSON string — it is raw text that your program receives from a file, an API, or localStorage. On the right, you see a JavaScript object that lives in your program's memory, ready for you to access properties like student.name or student.hobbies[0]. The two arrows show that conversion goes both directions. You parse when you receive text and need to work with it as data. You stringify when you have data and need to store or transmit it as text.

How It Works — Syntax & Mechanics

JSON.parse() — String to Object

The JSON.parse() method accepts a JSON-formatted string as its argument and returns the corresponding JavaScript value. If the input is a valid JSON object, you get back a JavaScript object. If it is a valid JSON array, you get back a JavaScript array. The method also accepts a second optional argument called a reviver function, which lets you transform values during parsing, but that is an advanced feature you will encounter later.

PARSE SYNTAX
const result = JSON.parse( jsonString );
jsonString — a valid JSON string (type: string). result — the JavaScript object, array, number, string, boolean, or null that was encoded in the JSON.
⚠️ Common Error
If the string is not valid JSON, JSON.parse() throws a SyntaxError. Common mistakes include using single quotes instead of double quotes, adding a trailing comma after the last item, or forgetting to wrap keys in double quotes. Always validate your JSON structure before parsing.

JSON.stringify() — Object to String

The JSON.stringify() method does the reverse. You pass it a JavaScript value — typically an object or array — and it returns a JSON-formatted string. The method accepts two optional parameters: a replacer (a function or array that filters which properties to include) and a space value (a number or string that adds indentation for readability). Using JSON.stringify(obj, null, 2) is a popular trick for pretty-printing JSON with two-space indentation.

STRINGIFY SYNTAX
const jsonStr = JSON.stringify( value, replacer, space );
value — the JavaScript object or array to convert. replacer — optional; a function or array that controls which properties are included. space — optional; number of spaces for indentation (use 2 for readability).
💡 Values That Get Lost
When you stringify an object, any property whose value is undefined, a function, or a Symbol is silently omitted. If an array contains these values, they are replaced with null. This is important to remember: not everything in JavaScript can round-trip through JSON.

JSON-Safe vs. JSON-Unsafe Data Types

One of the trickiest parts of working with JSON is knowing which JavaScript values survive the stringify-then-parse cycle and which do not. The following diagram and table break down exactly what JSON supports and what gets lost in translation.

The green column shows the seven value types that are JSON-safe — they survive round-tripping. The red column shows JSON-unsafe values that are either omitted or converted to something else during stringification.
How selected values behave through a stringify → parse round trip
JS ValueAfter JSON.stringify()After Parsing Back
"hello""\"hello\"""hello" ✓ Same
42"42"42 ✓ Same
true"true"true ✓ Same
undefinedProperty omitted entirelyKey is missing ✗
new Date()ISO date stringA string, not a Date ✗

Worked Example — Student Records

Imagine you are building a small web app that stores student information in the browser's localStorage. Since localStorage can only store strings, you must stringify your data before saving and parse it back when loading. Let's walk through the entire process.

Saving and Loading Student Data with JSON
1
Step 1 — Create the JavaScript ObjectStart by creating a JavaScript object that holds the student's information. This object exists in memory and can be manipulated freely. const student = { name: "Malik", grade: 11, gpa: 3.8, courses: ["CS 1", "English", "Physics"], active: true };
A live JavaScript object with five properties, including a nested array.
2
Step 2 — Stringify the ObjectConvert the object to a JSON string using JSON.stringify(). const jsonStr = JSON.stringify(student); The variable jsonStr now holds: '{"name":"Malik","grade":11,"gpa":3.8,"courses":["CS 1","English","Physics"],"active":true}'
A single string containing all the data in JSON format — ready for storage.
3
Step 3 — Save to localStorageUse localStorage.setItem() to store the JSON string under a key name. localStorage.setItem("studentData", jsonStr); The string is now persisted in the browser. Even if the user refreshes the page, the data survives.
Data saved as a string in the browser's local storage.
4
Step 4 — Retrieve and ParseLater, retrieve the string and parse it back into a JavaScript object. const retrieved = localStorage.getItem("studentData"); const studentObj = JSON.parse(retrieved); Now studentObj is a full JavaScript object again.
A live JavaScript object identical to the original — you can access studentObj.name and get "Malik".
5
Step 5 — Use the DataAccess properties just like any other JavaScript object. console.log(studentObj.courses[0]); // "CS 1" console.log(studentObj.gpa > 3.5); // true The round trip is complete: object → string → stored → retrieved → string → object.
Full round trip successful — data is fully accessible as a JavaScript object.

JSON vs. Other Data Formats

JSON is not the only data interchange format in the world. Understanding how it compares to alternatives helps you appreciate why it became the default choice for web development and why other formats still have their place in specific scenarios.

JSON vs. XML vs. CSV — feature comparison
FeatureJSONXMLCSV
ReadabilityEasy to read with nested structureVerbose with opening/closing tagsSimple but flat — no nesting
Data TypesStrings, numbers, booleans, null, objects, arraysEverything is text (requires schemas for typing)Everything is text (no type info)
File SizeCompact — minimal syntax overheadLarge — redundant tags add bulkVery small — just commas and newlines
Nested DataYes — objects and arrays nest freelyYes — elements nest freelyNo — only rows and columns
JS IntegrationNative — built-in parse/stringifyRequires DOMParser or a libraryRequires manual splitting or a library
Best ForWeb APIs, configuration files, NoSQL databasesDocument markup, SOAP services, legacy systemsSpreadsheet data, simple tabular exports
✦ KEY TAKEAWAY
JSON hits the sweet spot between simplicity and power. It is more expressive than CSV because it supports nested structures, and it is far more compact than XML. Combined with JavaScript's built-in JSON.parse() and JSON.stringify(), this makes it the default choice whenever you need to move data between your code and the outside world.

Connection to Advanced Concepts

Once you are comfortable with basic parsing and stringifying, there is a whole world of advanced techniques that build on these foundations. The table below previews how the core skills you have learned connect to more sophisticated patterns you will encounter in later courses and real-world projects.

From basics to advanced — where JSON.parse and JSON.stringify lead next
Basic Concept (This Lesson)Advanced Extension
JSON.parse(str)Using a reviver function as the second argument to transform date strings back into Date objects or convert values during parsing.
JSON.stringify(obj)Using a replacer function to filter out sensitive data (like passwords) before sending JSON to a server.
Storing data in localStorageUsing JSON with fetch() API to send and receive data from remote servers (REST APIs). The response body is parsed with response.json().
Flat JSON objectsDeeply nested JSON structures used in NoSQL databases like MongoDB, where entire documents are stored as JSON-like objects.
Manual error handling with try/catchUsing JSON Schema validation libraries to automatically verify that incoming JSON matches an expected structure before your code even attempts to parse it.

As you progress through your programming journey, you will find that virtually every web application relies on JSON for communication. Whether you are building a weather dashboard that fetches live forecast data, a multiplayer game that syncs player positions, or a social media feed that loads posts from a server, the pattern is always the same: receive JSON text, parse it into objects, work with the data, stringify updated objects, and send them back. Mastering these two methods now gives you a foundation that will serve you in every project ahead.

Practice Problems

PROBLEM 1 — CONCEPTUAL
A classmate says, "JSON and a JavaScript object are the same thing." Explain why this statement is incorrect, and identify at least two specific differences between a JSON string and a JavaScript object.
PROBLEM 2 — BASIC CALCULATION
Given the following JSON string, write the JavaScript code to parse it and then log the value of the city property to the console. const jsonStr = '{"city": "Denver", "state": "CO", "population": 715522}';
PROBLEM 3 — INTERMEDIATE
You have the following JavaScript object. Write code to stringify it with 2-space indentation, and then explain what happens to the greet property. const user = { name: "Priya", age: 17, greet: function() { return "Hi!"; }, score: undefined };
PROBLEM 4 — APPLIED
You are building a to-do list app. The user adds tasks, and you want to save the task array to localStorage so the tasks persist when the page reloads. Write a saveTasks() function and a loadTasks() function. The loadTasks() function should return an empty array if no data is found.
PROBLEM 5 — CRITICAL THINKING
A student runs this code and is surprised by the output. Explain why the round-trip does not produce an identical object, and suggest a solution. const event = { title: "Hackathon", date: new Date("2025-03-15") }; const json = JSON.stringify(event); const copy = JSON.parse(json); console.log(copy.date instanceof Date); // ??? console.log(typeof copy.date); // ???

Lesson Summary

JSON (JavaScript Object Notation) is a lightweight, text-based data format that uses key-value pairs and arrays to represent structured data. JavaScript provides two built-in methods for converting between JSON text and live data: JSON.parse() transforms a JSON string into a JavaScript object or array, while JSON.stringify() transforms a JavaScript object or array into a JSON string. These two methods form the bridge between data your program can manipulate and text that can be saved to localStorage, sent to a server, or received from an API.

Not all JavaScript values are JSON-safe — functions, undefined, and Symbol values are silently dropped during stringification, and Date objects become strings that do not automatically convert back into Dates. Understanding these edge cases is critical for writing reliable code. Use the space parameter in JSON.stringify(obj, null, 2) for readable output, and always wrap JSON.parse() in a try/catch block when parsing data from untrusted sources to handle potential SyntaxErrors gracefully.

Varsity Tutors • Computer Programming 1 (JavaScript) • JSON Parse & Stringify