PYTHON

JSON (JavaScript Object Notation) is not a programming language.

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:

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:
  • Downside: whitespace sensitivity can cause errors.

2. XML (Extensible Markup Language)

  • Heavier, older.
  • Used in older APIs, especially in enterprise systems.
  • 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:

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.
RECOMMENDED  Lesson 1: Python is Your Pet Snake; It Does Whatever You Tell It

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:

Beautiful, right? No brackets, no quotes unless needed. Super clean. But
 it came with its own set of problems.

  1. 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.
  2. YAML tries too hard to guess.
    If you write this in YAML:

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.”

  1. 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.
  2. 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


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:

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.

RECOMMENDED  🐍 PYTHON 101: “Quick & Easy Vocab"

3. JSON string → Python object

json.loads() — “take this JSON string, JSON, and give me a Python dict


4. Read JSON file → Python

json.load() — “Read the contents of the file and convert the JSON inside it into a Python object.”


5. Python object → Write to JSON file

json.dump() — “dump this JSON into a file.”

In plain English:

“Take this Python object and write it into a file as JSON.”


6. Types mapping (Python ↔ JSON)


7. Extra options in dumps()

Sort keys alphabetically:

Compact (minified) JSON:

  • Sorting keys alphabetically

If you want the output JSON to be predictable (e.g. for comparison, logging, etc.):

Output:


  • Compact / minified JSON

Saves space by stripping unnecessary whitespace—great for APIs or saving to disk:

Output:


  • Ensuring ASCII-only characters

If you’re sending data where non-English characters might break stuff:

Output:

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.

Output:

(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:


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.

Decode numbers as Decimal in Python

Output:


→ 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).”


→ 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.


→ 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.”


→ You’re asking Python:
“Show me what that decoded JSON looks like now as a Python dictionary.”


→ 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.”

RECOMMENDED  How to use len() in Python: 👀 Real Reasons You’d Use len()

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

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:


10. Handle invalid JSON (try/except it)

With,

→ 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.”

→ 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


12. JSON with Unicode characters

Python handles it by default, but you can force ASCII-only:

Or keep emojis + accents intact:

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 â˜ș)?

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


→ “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

  • 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:

Usage:

Check out how you’re going to use JSON when you’re building your AI Agents.

Spread the love

You'll also like...