Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 · JSON

Reading and Writing JSON in Python, Java and PHP Back Ends

See how a back end reads and writes the JSON your front end sends: json in Python, Jackson in Java, json_encode and json_decode in PHP, and how types match across the wire.

Your browser code is only half of an AJAX conversation. On the other side a server written in Python, Java, PHP, C#, Ruby or Go reads the JSON you send and writes the JSON you receive. Knowing how those languages handle JSON explains many bugs you see in the browser: a number that arrives as a string, a date that comes back as an array of numbers, an empty list that turns into {}, an error page in HTML where you expected JSON.

This lesson shows the basic read and write operations in three popular back-end languages, then lists the places where types do not match across the wire. Every example here ran on the same runner that powers the editors on this page. You do not need to write a back end to use the tutorial, but you will be a much better front-end developer after you have seen both sides.

One format, many languages

Python json.loads and json.dumps.
Java Jackson ObjectMapper.
PHP json_decode and json_encode.
1 / 2

The mapping between JSON and language types

Each language maps the six JSON types onto its own:

JSON JavaScript Python Java (Jackson) PHP
object object dict Map, record or class associative array or stdClass
array array list List indexed array
string string str String string
number number (a double) int or float int, long, double, BigDecimal int or float
true / false boolean True / False boolean true / false
null null None null null

Keep this table in mind: the rest of the lesson shows where it surprises people.

Python: the json module

Python ships with json. json.loads(text) parses a string, json.dumps(value) writes one, and the load and dump versions work with files. A parse error raises json.JSONDecodeError with the position.

Python Python: loads, dumps and default=

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the last line: Python writes NaN, which JavaScript's JSON.parse rejects. Pass allow_nan=False so the server fails loudly instead of sending something the browser cannot read. Also look at the default= hook: it is Python's counterpart of the replacer from Revivers, Replacers and toJSON.

In a web framework you usually do not call json yourself: Flask's jsonify, Django's JsonResponse and FastAPI's return values do it, and also set Content-Type: application/json. For the Python side of the full picture, see the Flask and Django tutorials.

Java: Jackson

Java has no JSON parser in the standard library, so projects add one. The most common is Jackson (ObjectMapper); Gson from Google is the other well-known choice. With Jackson you can read JSON into a generic tree (JsonNode) or map it to your own class or record, and write any object back.

Java Java: Jackson tree, records and dates

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two things to notice. First, dates: without the JavaTimeModule and WRITE_DATES_AS_TIMESTAMPS disabled, Jackson would write [2025,3,14] or a number, and your JavaScript would receive an array instead of a string. Second, unknown properties: by default Jackson rejects JSON that has fields your class does not declare; many projects turn that off for input from clients, and keep it strict for configuration files.

In Spring Boot you rarely create the mapper yourself: a controller method that returns an object or record is serialized by an auto-configured Jackson, and @RequestBody parses the incoming JSON the same way. Gson users write new Gson().toJson(obj) and new Gson().fromJson(text, User.class), which follow the same ideas. See JSON in Java with Jackson in the Advanced Java tutorial for a full treatment.

PHP: json_encode and json_decode

PHP has JSON built in. json_decode($text, true) returns an associative array (leave out true to get stdClass objects), and json_encode($value) returns a string. By default, errors do not throw; the functions return null or false and you must call json_last_error(). The modern way is the flag JSON_THROW_ON_ERROR, which raises a JsonException.

PHP PHP: decode, encode, flags and pitfalls

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first two pitfalls are the ones that bite front ends: JavaScript expects tags to be an array in both cases but may get {} when PHP builds the structure differently, and an array indexed from 1 or with gaps becomes an object with numeric keys that your .map() call cannot use. In Laravel, API resources and response()->json() handle the headers; the Laravel and PHP lessons go deeper.

Types that do not match across the wire

Most "my API is broken" reports come from a handful of mismatches. Decide each convention once and write it into your API documentation.

Problem What happens A good convention
Dates JSON has no date type; languages emit timestamps, arrays or local formats ISO 8601 strings in UTC (2025-03-14T09:30:00Z)
Large integers JavaScript numbers lose precision beyond 2^53 (about 9 quadrillion), so a 64-bit ID is silently changed send IDs above that range as strings
Money and decimals 0.1 + 0.2 is 0.30000000000000004 in binary floating point send cents as an integer, or a decimal as a string
Empty values null, missing key, empty string and empty list all mean different things document which one you use, and keep it consistent
Property names snake_case in Python, camelCase in Java and JavaScript pick one for the API and convert at the edge (a Jackson naming strategy, a serializer option)
Booleans some code uses 1/0 or "true" strings only real true and false
Unicode non-ASCII text may be escaped as \uXXXX always decode with a JSON parser; the result is the same text
Content type the server sends HTML (an error page) with status 200 always Content-Type: application/json; check it in the browser as in Debugging AJAX

Notice how many of these are fixed with the same technique: agree on a convention, validate on both sides (see JSON Schema), and cover it with a test that sends a real payload through both ends.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. In Python, what does json.dumps({"city": "Zürich"}) produce by default?

    ensure_ascii is true by default, so non-ASCII characters are escaped. A JSON parser turns the escape back into the same text.
  2. 2. What is the safest way to detect bad JSON in PHP 7.3 and newer?

    Without the flag, json_decode returns null for both invalid JSON and the valid JSON text null.
  3. 3. Why can Jackson give a JavaScript client [2025,3,14] for a date?

    Register JavaTimeModule and disable WRITE_DATES_AS_TIMESTAMPS to produce ISO strings.
  4. 4. A PHP array [1 => 'a', 2 => 'b'] is encoded as JSON. What does the client receive?

    Only lists with keys 0..n-1 become JSON arrays. Use array_values() to reindex first.
  5. 5. What is a sound way to send a 64-bit database ID to a JavaScript client?

    IDs are labels, not quantities, so a string is safe and avoids silent rounding.

Summary

  • Every back end maps JSON to its own types: Python dict/list, Java Map/records/JsonNode, PHP arrays or stdClass.
  • Use json.loads/dumps (with default= and allow_nan=False) in Python, Jackson's ObjectMapper (with the java.time module) in Java, and json_decode/json_encode with JSON_THROW_ON_ERROR in PHP.
  • Watch the mismatches: dates, large integers, decimals, empty values, naming style, and PHP's empty-array and gap-in-keys behavior.
  • Agree on conventions, put them in your API docs, validate on both sides and test with real payloads.

Next: send data when the page is going away in Beacons, keepalive and Sending Data on Page Exit.