Coding Tutorials

JSON explained: read, write and debug JSON data

Flat illustration of structured JSON data with keys, values, lists and nested objects

JSON is a text format for holding structured data, such as a user record, a list of posts, or the settings for a program. The name stands for JavaScript Object Notation, and the format uses curly brackets for objects, square brackets for lists, and pairs of keys and values to name each piece of data. Most web APIs send data in JSON, and most programs that read that data can turn JSON text into values they can work with.

JSON is useful because it is both readable by people and easy for programs to parse. A person can open a JSON file and see the keys, the values, and how they nest inside each other. A program can read the same text and turn it into a dictionary, a list, or a matching structure in its own language. That shared readability is the reason JSON is used for data exchange between programs written in different languages.

Read a JSON object, piece by piece

Start with one user record. The outer curly brackets say the whole thing is one object. Inside, each line holds a key, a colon, and a value. The key names the field, and the value holds the data for that field. Commas separate the pairs, and there is no comma after the last pair.

{
  "name": "Ayesha",
  "age": 29,
  "city": "Lahore",
  "subscribed": true
}

Read the types as you go. The name and city are text, so they sit in double quotes. The age is a number, so it sits without quotes. The subscribed value is true, which is a JSON value on its own, not text, so it also sits without quotes. That difference matters, because a program that reads this record will treat "29" as text and 29 as a number, and those two values behave differently in code.

{
  "title": "First post",
  "tags": ["python", "beginners"],
  "author": {
    "name": "Ayesha",
    "city": "Lahore"
  }
}

Write JSON with the rules that matter

JSON has a small set of strict rules, and they are worth learning exactly. Keys must be in double quotes, with no single quotes as a substitute. Text values must also use double quotes. A trailing comma after the last item in an object or a list is not allowed, even though some programming languages allow it in their own code. Comments are not allowed in JSON either, so a note written into a JSON file will break parsing, even if the note looks harmless to a person.

The values allowed in JSON are limited. Text, numbers, true, false, and null are the simple values. Lists and objects are the compound values. Null means the value is deliberately empty, which is different from missing the key entirely and different from an empty text value. That distinction is useful in data exchange, because a missing key may mean the sender never set the field, while null may mean the sender set it to empty on purpose.

The guide on Python dictionaries helps here, because a JSON object maps closely to a Python dictionary, with keys and values in the same shape. The guide on reading and writing files is also useful, because JSON data often lives in a file, and the steps for opening that file are the same whether the content is plain text or JSON. The APIs guide explains where JSON usually comes from in a web program, which is a response body sent by another program.

A worked example: parse and write JSON in Python

Python includes a json module that turns JSON text into Python values and turns Python values back into JSON text. The example below starts with a JSON string, parses it into a dictionary, prints one field, changes a value, and writes the result back into JSON text. Each step is small, and each step can be checked on its own.

import json

text = '{"name": "Ayesha", "age": 29, "city": "Lahore"}'
data = json.loads(text)
print(data["name"])
data["city"] = "Karachi"
print(json.dumps(data))
Ayesha
{"name": "Ayesha", "age": 29, "city": "Karachi"}

The loads function reads JSON text and returns Python values, with objects becoming dictionaries and lists becoming Python lists. The dumps function does the reverse, turning Python values into JSON text. The names are easy to mix up, so remember that loads works on a string, and dumps produces a string.

Debug JSON when parsing fails

When JSON text breaks the rules, parsing stops with an error that names the problem in general terms and often points at a position in the text. The fastest way to find the problem is to look at that position and the characters just before it. A missing comma is the usual cause when a new key starts right after a value with no separator.

SymptomLikely causeWhat to check first
Error near a keyMissing comma before that keyThe line above it, for a comma after the previous value
Error at the end of the textMissing closing bracket or braceCount opening and closing brackets, from the outside in
Error on a text valueSingle quotes, or an unescaped quote inside the textWhether text uses double quotes throughout
Data reads as text, not a numberNumber written inside quotesWhether numeric values sit without quotes

Common mistakes to watch for

The most common mistake is a trailing comma after the last item, often added by habit from code in another language. JSON does not allow it, and the parser will stop at that point. A second common mistake is using single quotes for keys or text values. JSON requires double quotes, and a document that uses single quotes is not valid JSON, even if it looks right to a reader used to Python or JavaScript code.

A third mistake is writing a comment inside JSON to explain a field. Comments are a useful habit in code, but JSON has no comment syntax, so the parser treats the comment text as data and fails. Keep explanations outside the JSON file, in the code that reads it or in separate documentation. A fourth mistake is confusing null, missing, and empty. A key set to null, a key left out, and a key set to empty text are three different states, and code that treats them as the same thing will behave wrongly on some records.

A fifth mistake is assuming that numbers in JSON keep their exact form after parsing. A program may read a large number or a decimal and store it in its own number type, which can change how it prints. That is a property of the program reading the data, not a fault in the JSON text, and it matters when the number is an identifier or a precise amount.

Limits of this guide

This guide covers reading, writing, and debugging JSON for everyday data, such as records, lists, and settings. It does not cover JSON Schema, which is a separate way to describe the expected shape of JSON data, or streaming JSON for very large files, because those topics need larger examples and a real project to practise against.

Worked example: build JSON from a Python dictionary

Building JSON in Python starts from a dictionary, because the two shapes map closely. Keys become JSON keys, text becomes JSON strings, numbers stay numbers, and nested dictionaries become nested JSON objects. The example below dumps a dictionary to a JSON string with indentation, which makes the result readable, and then loads it back to confirm the round trip works.

import json

person = {"name": "Maya", "age": 18, "tags": ["student", "coder"]}
text = json.dumps(person, indent=2)
print(text)
back = json.loads(text)
print(back["name"])

The dumps call turns the dictionary into text, while loads turns text back into a dictionary. That pair is the core of JSON work in Python, and most JSON tasks reduce to choosing the right side of that pair. Dumping is used when data must be saved or sent, loading is used when data arrives as text and must be used as structured data.

Indentation is a display choice, not a data choice. A dumped string with indent 2 and one without it hold the same data, yet the indented form is easier to read while debugging, and the compact form is smaller for sending. For files that a person may read, the indented form is the better default, while for data sent over a network, the compact form saves space without changing meaning.

JSON types and Python types in a table

JSON has a small set of types, and each one maps to a Python type in a predictable way. The table below lists those mappings, which matter because a value that crosses the JSON boundary changes type in that mapping, and a program that expects the original Python type may be surprised. A Python tuple, for example, becomes a JSON array, and it loads back as a list, rather than as a tuple.

JSON typePython type after loadingNote
ObjectdictKeys are always strings
ArraylistOrder is kept
StringstrText in double quotes
Numberint or floatNo distinction between int and float in JSON itself
true, falseTrue, FalseLower case in JSON, capitalised in Python
nullNoneMeans no value

Keys deserve a special note. JSON object keys are always strings, so a Python dictionary with number keys will dump those keys as strings, and loading the result will give string keys rather than the original number keys. A program that looks up a loaded value by a number key will then miss, because the key is now text. Converting keys back after loading, or using string keys from the start, avoids that trap.

Dates have no JSON type of their own, so programs store them as strings in a consistent format, and parse them back after loading. That choice must be agreed between the writer and the reader, because a date string in one format will not parse in a program expecting another. Using a widely recognised format, and documenting it beside the data, keeps the date readable and parseable on both sides.

Debug JSON with a validator and a line number

When loading fails, the error message usually includes a line and column number, which points at the spot where the parser gave up. That spot is often just after the real mistake, such as a missing comma on the previous line, so reading the line before the reported position is part of the fix. A JSON validator, which checks a text against the JSON rules and highlights the first problem, gives the same help in a visual form.

Common JSON mistakes have a short list. A trailing comma after the last item in an object or array is not allowed, single quotes are not allowed for strings, and unquoted keys are not allowed. Each of those forms is valid in Python, which is why a Python dictionary copied into a JSON file often fails. Checking the text against the JSON rules, rather than the Python rules, catches those three mistakes quickly.

When a JSON file is large, narrowing the problem helps. Copying a small section around the reported line into a validator, or splitting the file into parts, shows whether the problem sits in one section or in the overall shape. That narrowing step is faster than reading a long file from the top, because the error position already gives a starting point close to the mistake.

JSON in files, and handling missing fields after loading

Saving JSON to a file uses the same dumps and loads pair, with file reading and writing around it. The dump call writes the JSON text to a file opened for writing, and the load call reads a file opened for reading and parses its content. Using with for both operations closes the file cleanly, and specifying UTF-8 encoding keeps non-English text readable on both sides.

import json

data = {"name": "Maya", "score": 18}
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)

with open("data.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded)

After loading, fields may be missing, because the file was written by an older version of the program or by a different source. Accessing a missing field directly raises a KeyError, so a program that reads outside data should use get with a default, or check for the key before using it. That defensive reading keeps the program running on older files, while still surfacing a clear value when a field is absent.

Nested fields need the same care at each level, because a missing outer field makes the inner lookup fail as well. Chaining get calls with defaults, or checking each level before going deeper, prevents a crash deep inside a data structure. For data with many optional fields, a small helper that walks a path of keys and returns a default when any level is missing keeps the reading code short and consistent.

Frequently asked questions

Is JSON the same as a Python dictionary?

No, though they look similar. JSON is text that follows strict rules, while a Python dictionary is a value in a running program. The json module converts between the two, and the conversion is where the rules matter, such as double quotes for keys and no trailing commas.

Why does my JSON fail when it looks fine?

Look for a trailing comma, single quotes, or a missing closing bracket first, because those three problems cause most parse errors. Reformat the text with indentation to make nesting visible, then check the spot the error message points at and the characters just before it.

Should numbers be quoted in JSON?

Only when they should be treated as text, such as an identifier that must keep its exact form. Numbers meant for arithmetic should sit without quotes, so the program reading them treats them as numbers. Check the API or file documentation when you are unsure, because that documentation defines the expected type for each field.

How do I store a date in JSON?

Store a date as a string in a consistent format, because JSON has no date type of its own. Both the writer and the reader must agree on that format, so the date can be parsed back after loading.

What happens to a tuple when it is dumped to JSON?

A tuple becomes a JSON array, and it loads back as a list rather than as a tuple. A program that expects a tuple after loading should convert the loaded list back, or use a list from the start.

How do I read JSON from a file instead of a string?

Open the file for reading and use json.load on the file object, rather than json.loads on a string. The load call reads the file content and parses it in one step, and using with closes the file cleanly afterward.

Sources