JSON (JavaScript Object Notation) is not a programming language.
Itâs just a way to format and organize data so computers and humans can both read it easily. Kind of like a labeled storage locker with individual compartments.
Example JSON:
{
"name": "Beyoncé",
"age": 42,
"isSinger": true,
"albums": ["Lemonade", "Renaissance"]
}
It uses:
- Curly braces
{}
for carrying or containing groups of things that are related - Key-value pairs (
"name": "Beyoncé"
) - Square brackets
[]
for lists (like albums)
How’s JSON different from programming languages?
A: JSON doesnât âdoâ anything. No logic, no loops, no functions. It just holds data. Thatâs it.
B: A programming language (like Python, JavaScript, etc.) actually runs code, makes decisions, moves data around, and does stuff with it.
C: JSON is what youâd use within a programming language to store or exchange dataâlike handing over a nicely labeled box to another program or API.
JSON is really just a delivery format, and programming languages are the “people” that unpack it, use the stuff inside, and make decisions.
You know how two people who speak different languages need a translator to talk? Computers and apps are the sameâthey need a shared format they both understand.
Thatâs where things like JSON and YAML come in. Theyâre just text formats. They’re like languages made only for passing around info.
So whenever two systems want to exchange data (like, say, your phone app asking a server for your messages), that data needs to be written in one of these âuniversalâ formats.
Itâs like the suitcase they pack the info into. JSON is that suitcase, and for the last decade or so, it’s been the one almost everyone grabs off the shelf.
You can use JSON with pretty much any modern programming language.
Languages like Python, JavaScript, Go, C#, Ruby, Rustâall of them can read from and write to JSON.
- Itâs simple.
- Itâs language-agnostic.
- Itâs lightweight.
Before JSON was common, people mostly used XMLâwhich looks a bit like HTML, but messier. You had to wrap everything in tags (<this></this>
), and it was very rule-heavy. You needed special tools just to read it properly. And writing it? Ugh. Felt like filling out tax forms in code.
Then around the mid-2000s, the web started shifting. JavaScript became the language of the browser. And JavaScript had its own way of writing dataâbasically, just like how JSON looks. The people building websites realized: âWait⊠why not just use this style to pass data around?â
That âstyleâ was JSON. It looked just like what they were already using in JavaScript code. No converters. No extra steps.
Alternatives to JSON (aka other data formats that do the same job):
Depending on the job:
1. YAML (Yet Another Markup Language)
- More readable, less punctuation.
- Popular in config files (e.g., GitHub Actions, Docker).
- Example:
name: Beyoncé
age: 42
isSinger: true
albums: - Lemonade - Renaissance
- Downside: whitespace sensitivity can cause errors.
2. XML (Extensible Markup Language)
- Heavier, older.
- Used in older APIs, especially in enterprise systems.
- Example:
person>
<name>Beyoncé</name>
<age>42</age>
<isSinger>true</isSinger>
<albums>
<album>Lemonade</album>
<album>Renaissance</album>
</albums>
</person>
- Verbose and kind of annoying, but still used in banking, government, legacy stuff.
3. TOML (Tomâs Obvious Minimal Language)
- Used in config files for Rust and Python projects (like
pyproject.toml
). - Clear structure, less noisy than JSON.
- Example:
name = "Beyoncé"
age = 42
isSinger = true
albums = ["Lemonade", "Renaissance"]
4. Protocol Buffers (Protobuf) by Google
- Super compact, fast, but not human-readable.
- Great for high-performance apps and internal data passing.
- Needs special tools to serialize/deserialize.
5. MessagePack
- Like JSON but binary and more compact.
- Used where speed and size matter (IoT, mobile, etc).
TL;DR:
- JSON is the crowd favorite because itâs easy, universal, and readable.
- YAML is more human-friendly.
- XML is the grandpa still hanging around in big old systems.
- Protobuf and MessagePack are fast and efficient but not human-friendly.
{
“name”: “BeyoncĂ©”,
“age”: 42
}
Thatâs readable. Itâs short. Itâs obvious what it means. Andâthis was hugeâevery programming language started supporting it. So it wasnât just good for websites anymore. Now any app could use itâPython, Java, mobile apps, backend servers, all of it.
Developers started ditching XML and switching to JSON because it was shorter (less typing), it didnât need complicated software to read, JSON made debugging easierâyou could just open a file and immediately get what it meant.
And it didnât require a special setup to âparseâ or understand.
And at the same time, websites started building more flexible APIs (which are like menu systems for developers to ask for data). These newer APIs needed a simple, fast, and consistent format. JSON clicked into place like a puzzle piece.
Then why didnât YAML win?
So YAML came along too, and on paper, itâs even nicer to read than JSON. Look at this:
name: Beyoncé
age: 42
Beautiful, right? No brackets, no quotes unless needed. Super clean. But⊠it came with its own set of problems.
- Spacing is risky.
In YAML, the number of spaces mattersâa lot. You accidentally add one space in the wrong spot, and your whole file might break, and the error messages you get? Useless. In JSON, everything is wrapped in brackets and commas. Itâs strictâbut that strictness helps avoid accidental mistakes. - YAML tries too hard to guess.
If you write this in YAML:
yes: true
date: 2025-04-12
Itâll automatically guess that yes means the boolean true, and that the date is a real dateânot a string. That can backfire. What if you wanted “yes” to literally be the word âyesâ? Or the date to stay in quotes? Youâd have to write extra stuff just to prevent YAML from being âhelpful.â
- Too powerful for its own good.
YAML can actually define custom objects, functions, even commands. That opens the door to security issuesâespecially if someone sends you YAML and you try to open it blindly. JSON? Doesnât try to do anything clever. Just holds basic data. That makes it boring, but very safe. - Machines donât like it as much.
YAML was designed to make things easier for humans to read, not for machines to parse. That makes it a bit heavy-duty under the hood. JSON is the oppositeâitâs not as pretty, but it’s very efficient for machines to work with.
Where do things stand now?
JSON is used for:
APIs, mobile apps, web services, AI agents, databases, logs, and basically anything that moves data from one place to another.
YAML is used for:
Developer tools, configs you hand-write (like GitHub Actions, Docker, Kubernetes). When people need to read and edit files manually, YAML is nice.
But you donât send it over the internet or parse it on-the-fly for real-time apps. Too fragile.
Python + JSON cheat sheet
1. Import the JSON module
import json
2. Python object â JSON string
json.dumps()
â “stringify this your way, JSON”.
data = {
"name": "Beyoncé",
"age": 42,
"isSinger": True,
"albums": ["Lemonade", "Renaissance"]
}
json_string = json.dumps(data)
In plain English:
âTurn the data
Python object into a JSON-formatted string and store it in a variable called json_string
.â
Pretty-print it:
print(json.dumps(data, indent=2))
The Python object in that example is this dictionary:
data = {
"name": "Beyoncé",
"age": 42,
"isSinger": True,
"albums": ["Lemonade", "Renaissance"]
}
That data
variable is a Python dict
, which is:
- Made up of key-value pairs (
"name": "Beyoncé"
etc.), - Can contain strings, numbers, booleans, lists, other dicts, etc.,
- And it’s exactly the kind of thing
json.dumps()
knows how to turn into a JSON string.
You could swap in any other valid Python object (as long as it’s JSON-serializable)âlike a list of dicts, a nested structure, or just a plain listâand json.dumps()
would still handle it.
3. JSON string â Python object
json.loads()
â “take this JSON string, JSON, and give me a Python dict“
json_data = '{"name": "Beyoncé", "age": 42, "isSinger": true}'
data = json.loads(json_data)
4. Read JSON file â Python
json.load()
â âRead the contents of the file and convert the JSON inside it into a Python object.â
with open("data.json", "r") as file:
data = json.load(file)
5. Python object â Write to JSON file
json.dump()
â “dump this JSON into a file.”
with open("data.json", "w") as file:
json.dump(data, file, indent=2)
In plain English:
âTake this Python object and write it into a file as JSON.â
6. Types mapping (Python â JSON)
Python | JSON |
---|---|
dict | Object |
list, tuple | Array |
str | String |
int, float | Number |
True/False | true/false |
None | null |
7. Extra options in dumps()
Sort keys alphabetically:
json.dumps(data, sort_keys=True)
Compact (minified) JSON:
json.dumps(data, separators=(",", ":"))
- Sorting keys alphabetically
If you want the output JSON to be predictable (e.g. for comparison, logging, etc.):
pythonimport json
data = {
"age": 24,
"name": "Tate McRae",
"albums": ["Think Later", "I Used to Think I Could Fly"]
}
json_string = json.dumps(data, sort_keys=True, indent=2)
print(json_string)
Output:
json{
"age": 24,
"albums": [
"Think Later",
"I Used to Think I Could Fly"
],
"name": "Tate McRae"
}
- Compact / minified JSON
Saves space by stripping unnecessary whitespaceâgreat for APIs or saving to disk:
pythoncompact = json.dumps(data, separators=(",", ":"))
print(compact)
Output:
json{"age":24,"name":"Tate McRae","albums":["Think Later","I Used to Think I Could Fly"]}
- Ensuring ASCII-only characters
If youâre sending data where non-English characters might break stuff:
pythonascii_safe = json.dumps({"name": "Sabrina Carpenter"}, ensure_ascii=True)
print(ascii_safe)
Output:
json{"name":"Sabrina Carpenter"}
FYI: This is more relevant if you’re dealing with characters like Ă©, ñ, ĂŒ etc.
- Skipping
None
values
Pythonâs None
becomes null
in JSON, but sometimes you want to ignore them entirely.
pythondata = {
"name": "Carlie Hanson",
"age": None,
"genre": "Pop"
}
cleaned = {k: v for k, v in data.items() if v is not None}
json_string = json.dumps(cleaned)
print(json_string)
Output:
json{"name": "Carlie Hanson", "genre": "Pop"}
(There’s no built-in flag for this in json.dumps()
itself, so we use a quick dictionary cleanup.)
- Pretty-print with custom indentation
Make it readable but more compact than indent=2
:
pythonprint(json.dumps(data, indent=1))
8. Decode numbers as Decimal
(for precise math)
When youâre dealing with numbers in JSON, Python usually turns them into floatsâbut floats can get imprecise with decimals (like with money, scientific data, anything where 0.1 + 0.2
being 0.30000000000000004
is just not cute).
To get around that, Python lets you decode JSON numbers as Decimal
objects (from the decimal
module) instead of regular floats.
from decimal import Decimal
data = json.loads('{"price": 19.99}', parse_float=Decimal)
Decode numbers as Decimal
in Python
pythonimport json
from decimal import Decimal
json_string = '{"price": 19.99, "tax": 0.07}'
# Tell the parser to load floats as Decimal
data = json.loads(json_string, parse_float=Decimal)
print(data)
print(type(data["price"])) # <class 'decimal.Decimal'>
Output:
python{'price': Decimal('19.99'), 'tax': Decimal('0.07')}
<class 'decimal.Decimal'>
pythonimport json
from decimal import Decimal
â Youâre telling Python:
âHey, I need the json module (so I can read JSON stuff) and the Decimal class (so I can handle numbers very precisely; no float nonsense).â
pythonjson_string = '{"price": 19.99, "tax": 0.07}'
â Youâve got a string that looks like a JSON object. Itâs just text right now, not usable data. It represents a price and taxâboth decimal numbers.
pythondata = json.loads(json_string, parse_float=Decimal)
â Youâre saying:
âTake that JSON string and load it into Python as a dictionary, but here’s the twistâdonât treat the numbers like floats (which might mess up rounding). Instead, treat them as Decimal objects so the precision stays perfect.â
pythonprint(data)
â Youâre asking Python:
âShow me what that decoded JSON looks like now as a Python dictionary.â
pythonprint(type(data["price"]))
â And now you’re double-checking:
âTell me what kind of thing this price
value is. Is it a float? Is it a Decimal? I wanna make sure it actually worked.â
In short:
You’re taking raw JSON text â turning it into Python data â and telling Python to treat all decimal numbers with care by storing them as Decimal
instead of regular floats.
- Floats can lose precision (especially after a few calculations).
Decimal
keeps every decimal point intactâperfect for currency, billing, or anything math-heavy where errors stack up.- This doesn’t affect how the JSON looksâitâs just about how Python treats the numbers after loading.
You can do the same with
parse_int=Decimal
if you’re worried about super long numbers or want everything handled as Decimal
.
9. Handle non-serializable types (e.g., datetime)
Python canât auto-serialize stuff like datetime
, so use custom handlers:
import datetime
def custom_serializer(obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
raise TypeError("Type not serializable")
data = {
"event": "Release",
"time": datetime.datetime.now()
}
json.dumps(data, default=custom_serializer)
10. Handle invalid JSON (try/except it)
try:
data = json.loads(possibly_broken_json)
except json.JSONDecodeError:
print("Oops. That ain't JSON.")
With,
pythontry:
data = json.loads(possibly_broken_json)
â youâre telling Python,
âOkay, Iâm going to try loading this thing into real data using json.loads()
. Fingers crossed itâs not trash.â
pythonexcept json.JSONDecodeError:
print("Oops. That ain't JSON.")
â And if it is trash (like, not valid JSON), Python will say,
âYow, something went wrong here… but instead of crashing and screaming errors, Iâm just going to politely say:
‘Oops. That ain’t JSON.’â
Without try/except
, Python would freak out and stop your entire program if the JSON is broken.
But with it, youâre giving Python backup instructions:
âIf it fails, just keep going and tell me nicely.â
This is great if youâre:
- Reading data from outside sources (APIs, files, user input)
- Not in the mood to babysit a crash every time something’s malformed
- Doing anything that needs resilience and doesnât deserve a full meltdown
11. Convert back and forth just because
# Dict â String â Dict
s = json.dumps(data)
back = json.loads(s)
12. JSON with Unicode characters
Python handles it by default, but you can force ASCII-only:
json.dumps(data, ensure_ascii=True)
Or keep emojis + accents intact:
json.dumps(data, ensure_ascii=False)
What even is a Unicode character?
Unicode characters = literally any character beyond basic English.
That means:
- Accents â
Ă©
,ñ
,Ăž
- Non-English alphabets â
æŒąć
,ŃŃŃŃĐșĐžĐč
,ۧÙŰč۱ۚÙŰ©
- Emojis â đđ„đ
- Symbols â
âą
,©
,§
,â
Basically, if itâs not plain olâ A-Z or 0-9 or a comma or period, itâs Unicode.
JSON started out in the web world, and not everything on the web speaks Emoji or Accent. Some older systems or APIs just want boring basic letters and canât read âđâ or âĂ©â.
JSON has a little toggle to decide:
- Should I keep the fancy characters as-is?
- Or should I convert them into ASCII-safe code (like
\u263a
instead ofâș
)?
pythonjson.dumps(data, ensure_ascii=True)
Translation?
â âWhen I turn this Python data into a JSON string, turn ALL non-English characters into escape codes.â
Yay, safe for strict systems
Er.. looks kinda ugly to humans
pythonjson.dumps(data, ensure_ascii=False)
â âLet the characters stay beautifulâkeep the emojis, accents, and symbols just how I typed them.â
Yay, looks great
Yay, perfect for readable data or sharing
Oops, might not work with ancient tech
pythondata = {"name": "Tate McRae", "mood": "đ„đ€", "city": "MontrĂ©al"}
ensure_ascii=True
gives you:'{"name": "Tate McRae", "mood": "\\ud83d\\udd25\\ud83c\\udfa4", "city": "Montr\\u00e9al"}'
ensure_ascii=False
gives you:'{"name": "Tate McRae", "mood": "đ„đ€", "city": "MontrĂ©al"}'
This trick is just about how the data looks when saved or sent somewhere.
13. JSONPath-style querying (not built-in, but useful)
Install with:
pip install jsonpath-ng
Usage:
from jsonpath_ng import jsonpath, parse
data = {
"users": [
{"name": "A", "age": 20},
{"name": "B", "age": 25}
]
}
expr = parse("$.users[*].name")
matches = [match.value for match in expr.find(data)]
Check out how you’re going to use JSON when you’re building your AI Agents.