the full guide

JSON and regular expressions

Read the data format the web runs on, and find patterns in text.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

JSON

JSON is how programs send data to each other. It looks almost exactly like a Python dictionary. When you call an AI model's API, the reply is JSON.

json_demo.py
import json

text = '{"name": "Riya", "marks": [78, 85], "passed": true}'

data = json.loads(text)        # Text to Python
print(data["name"], data["marks"][1])

data["city"] = "Pune"
print(json.dumps(data))        # Python back to text

Output

Riya 85
{"name": "Riya", "marks": [78, 85], "passed": true, "city": "Pune"}

Regular expressions

A regular expression describes a pattern. It's the standard tool for cleaning text before it goes into a model.

regex_demo.py
import re

text = "Call 98765 43210 or mail riya@example.com by 5 pm"

print(re.findall(r"\d+", text))                # Groups of digits
print(re.findall(r"\S+@\S+", text))            # Something like an email
print(re.sub(r"\d", "#", text))                # Hide the digits

Output

['98765', '43210', '5']
['riya@example.com']
Call ##### ##### or mail riya@example.com by # pm
PatternMatches
\dA digit
\wA letter, digit or underscore
\sA space
+One or more of the previous
*Zero or more of the previous
^ and $Start and end of the text

Finished reading?