File I/O & DataLesson 2 of 2
JSON & Regex
JSON and regular expressions are built into JavaScript as globals. In Python they are just as built in, but they live in standard library modules you import: json and re. (CSV is the one where JS usually needs an npm package; Python ships a csv module.)
The json module maps directly: JSON.parse() becomes json.loads() and JSON.stringify() becomes json.dumps(). The s at the end stands for string. For files there is a matching pair: json.load(file) reads from a file object and json.dump(obj, file) writes to one, with no intermediate string step.
JSON types map naturally: objects become dicts, arrays become lists, null becomes None, true/false become True/False. One difference: json.dumps() raises a TypeError for values it does not know, such as datetime, Decimal, or your own classes, where JSON.stringify would silently produce {} or call toJSON().
Python's regex module (re) uses a function-based API instead of regex literals. re.search() finds the first match anywhere, re.findall() returns all matches, re.sub() replaces (all matches by default), and re.fullmatch() checks the whole string. The trap: re.match() only matches at the START of the string, which confuses JS developers who expect it to search everywhere like str.match().
Quick reference
| JavaScript | Python | Note |
|---|---|---|
| JSON.parse(str) | json.loads(str) | s = from string |
| JSON.stringify(obj, null, 2) | json.dumps(obj, indent=2) | s = to string |
| fs + JSON.parse | json.load(f) / json.dump(obj, f) | Read/write file objects |
| str.match(/p/g) | re.findall(r"p", s) | All matches as a list |
| str.match(/p/) | re.search(r"p", s) | search = anywhere |
| str.replace(/p/g, r) | re.sub(r"p", r, s) | Replaces all by default |
| /p/.test(str) | bool(re.search(r"p", s)) | No .test() method |
Side by side
// JavaScript
const obj = JSON.parse(jsonString);
const str = JSON.stringify(obj, null, 2);
const match = text.match(/\d+/);
const all = text.match(/\d+/g);
const replaced = text.replace(/old/g, "new");
/^test/.test(text);# Python JSON (standard library)
import json
obj = json.loads(json_string) # parse
text = json.dumps(obj, indent=2) # stringify
with open("data.json", encoding="utf-8") as f:
data = json.load(f) # read file
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2) # write file
# Regex (standard library)
import re
match = re.search(r"\d+", text) # first match
if match:
print(match.group())
all_nums = re.findall(r"\d+", text) # all matches
replaced = re.sub(r"old", "new", text)
valid = bool(re.match(r"test", s)) # only at the start!Exercise
Real Python, running in your browserWrite Python code that:
Ctrl + Enter runCtrl + Shift + Enter checkTab indentEsc then Tab to leave the editorCtrl + / comment