Parsing JSON in JavaScript and Python
9 min read
JavaScript and Python are the two languages where most developers first meet JSON. Reassuringly, the core operations are nearly identical: parse text into a data structure, and serialise a data structure back into text. This guide puts the two side by side and covers the gotchas that catch people out.
Parsing: text to data
JavaScript uses JSON.parse():
const text = '{"name": "Ada", "id": 1, "active": true}';
const obj = JSON.parse(text);
console.log(obj.name); // "Ada"
console.log(obj.id); // 1Python uses json.loads() ("load string"):
import json
text = '{"name": "Ada", "id": 1, "active": true}'
obj = json.loads(text)
print(obj["name"]) # Ada
print(obj["id"]) # 1Note how JSON types map to native ones: object β dict/object, array β list/array, true β True/true, null β None/null.
Generating: data to text
JavaScript uses JSON.stringify():
const obj = { name: "Ada", id: 1 };
const text = JSON.stringify(obj);
// '{"name":"Ada","id":1}'
// pretty-printed with 2-space indent
const pretty = JSON.stringify(obj, null, 2);Python uses json.dumps() ("dump string"):
import json
obj = {"name": "Ada", "id": 1}
text = json.dumps(obj)
# '{"name": "Ada", "id": 1}'
# pretty-printed
pretty = json.dumps(obj, indent=2)Reading and writing files
Both languages have file-aware variants so you do not handle the text yourself.
// JavaScript (Node.js)
import { readFile, writeFile } from "node:fs/promises";
const data = JSON.parse(await readFile("in.json", "utf8"));
await writeFile("out.json", JSON.stringify(data, null, 2));# Python
import json
with open("in.json") as f:
data = json.load(f) # note: load, not loads
with open("out.json", "w") as f:
json.dump(data, f, indent=2)The pattern to remember: the s suffix means "string". loads/dumps work on strings; load/dump work on file objects.
Handling errors
Never trust external JSON to be valid. Wrap parsing in error handling so a malformed payload does not crash your program.
// JavaScript
try {
const obj = JSON.parse(input);
} catch (err) {
console.error("Invalid JSON:", err.message);
}# Python
try:
obj = json.loads(input)
except json.JSONDecodeError as err:
print(f"Invalid JSON at line {err.lineno}: {err.msg}")The dates gotcha
JSON has no date type. Both languages serialise dates as strings, and neither automatically turns a date-looking string back into a date object on parse. You must convert explicitly.
// JavaScript: dates become ISO strings
JSON.stringify({ when: new Date() });
// '{"when":"2026-06-26T08:00:00.000Z"}'
// parse it back manually:
const obj = JSON.parse(text);
obj.when = new Date(obj.when);# Python: datetime is NOT serialisable by default
import json, datetime
json.dumps({"when": datetime.datetime.now()})
# TypeError! pass default=str, or convert first:
json.dumps({"when": datetime.datetime.now().isoformat()})Other gotchas worth knowing
- Big integers: JavaScript loses precision above 2^53. Use
BigIntor keep large IDs as strings. Python integers are arbitrary precision, so it does not have this problem β which can cause mismatches between the two. - Key order: both preserve insertion order in practice, but JSON objects are formally unordered β never rely on order for correctness.
- NaN and Infinity: Python's
jsonemits these by default (invalid JSON!); passallow_nan=Falseto be strict. JavaScript turns them intonull. - Non-string keys: Python dict keys that are not strings get coerced to strings on dump; JSON keys are always strings.
Frequently asked questions
What is the difference between loads and load in Python?
json.loads() parses a JSON string; json.load() reads from a file object. The same distinction applies to dumps (to string) versus dump (to file).
Why does JSON.parse fail on a trailing comma?
Because JSON forbids trailing commas, even though JavaScript object literals allow them. JSON.parse() follows the strict JSON grammar. Remove the comma or use the Repair tool to fix it. See common JSON errors.
How do I pretty-print JSON in code?
Pass an indent: JSON.stringify(obj, null, 2) in JavaScript, or json.dumps(obj, indent=2) in Python. Both produce human-readable, indented output.
Test your output
Whatever you generate in code, you can paste into the JSON Wallet editor to confirm it is valid and readable before shipping it. To understand the format your code is producing, read What is JSON? and escaping and stringifying JSON.
Keep reading
What Is JSON? A Beginnerβs Guide
JSON is the most widely used data format on the web. This guide explains what it is, how it is structured, and where you will run into it as a developer.
JSON Syntax Rules Explained (With Examples)
JSON has a small but strict grammar. This reference walks through every rule with valid and invalid examples so your data parses the first time.
Common JSON Errors and How to Fix Them
Every developer hits "Unexpected token in JSON" eventually. Here are the most common JSON errors, what causes them, and exactly how to fix each one.
Ready to put this into practice? Open the free JSON editor β