Intermediate · Errors, modules and the standard library · topic 26 of 50 · 25 min
JSON and regular expressions
Explanation
JSON: data as text
JSON (JavaScript Object Notation) is a way to write data as plain text. It looks almost like Python dicts and lists. When a weather app or a payment app talks to its server, the data usually travels as JSON.
import json
order = {"id": 101, "item": "Masala Dosa", "paid": True, "note": None}
text = json.dumps(order)
print(text)
print(type(text))
back = json.loads(text)
print(back["item"])| Python | JSON |
|---|---|
| dict | object { } |
| list, tuple | array [ ] |
| str | string (always double quotes) |
| int, float | number |
| True / False | true / false |
| None | null |
import json
student = {"name": "Asha", "marks": [82, 91], "scholarship": False}
print(json.dumps(student, indent=2))
print(json.dumps({"b": 1, "a": 2}, sort_keys=True))Regular expressions
A regular expression (regex) is a short pattern that describes text, such as "one or more digits". Write patterns as raw strings, r"...", so Python leaves every backslash for the re module to read.
| Pattern | Matches |
|---|---|
| \d | one digit, 0 to 9 |
| \w | one letter, digit or underscore |
| . | any one character |
| [6-9] | one character from 6 to 9 |
| + | one or more of the thing before it |
| * | zero or more of the thing before it |
| ? | zero or one: the thing before it is optional |
| {6} | exactly 6 of the thing before it |
| \b | a word boundary: the edge of a word or number |
import re
text = "Call Ravi on 9876543210 or the office on 080-22334455."
m = re.search(r"[6-9]\d{9}", text)
print(m.group())
print(re.findall(r"\d+", text))
print(re.sub(r"\d", "X", "PIN 560001"))re.search looks for the pattern anywhere and gives a match object (or None). re.findall returns a list of every match. re.sub replaces each match. re.fullmatch checks that the whole text fits the pattern, which is what you want for checking a form field.
import re
def valid_mobile(s):
return re.fullmatch(r"[6-9]\d{9}", s) is not None
def valid_pin(s):
return re.fullmatch(r"[1-9]\d{5}", s) is not None
print(valid_mobile("9876543210"), valid_mobile("1234567890"))
print(valid_pin("560001"), valid_pin("056001"))Watch the lesson
JSON and regular expressions · 1/6
Two everyday tools for working with text: JSON for sending data, and regular expressions for finding patterns.
Prefer a video by a teacher? Find free videos on “python json and regular expressions re module tutorial” on YouTube ↗
In real life: Cleaning a contact list for an SMS reminder
A tuition centre has a messy text file of parent contacts. Kiran pulls out every valid Indian mobile number with one regex, then saves the result as JSON so the SMS app can read it.
import re, json
notes = """Ravi papa 98765 43210, Asha mummy 7012345678
office 080-22334455, old number 5123456789"""
clean = notes.replace(" ", "")
# (?<!\d) and (?!\d) mean: no digit just before or just after
mobiles = re.findall(r"(?<!\d)[6-9]\d{9}(?!\d)", clean)
print(json.dumps({"count": len(mobiles), "numbers": mobiles}, indent=2))Practice (0/3 done)
Write order_total(json_text). The text is JSON like {"items": [{"name": "Idli", "qty": 2, "price": 40}, ...]}. Return the total bill: the sum of qty × price for every item.
Write find_mobiles(text) that returns a list of every Indian mobile number in the text: exactly 10 digits, starting with 6, 7, 8 or 9, and not part of a longer number. Use re.findall with word boundaries \b.
Write valid_pin(pin) that returns True when pin is a valid Indian PIN code: exactly 6 digits, and the first digit is not 0. Use re.fullmatch.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.