Skip to content
Learn Netverks

Lesson

Step 16/36 44% through track

json-php

JSON encode and decode

Last reviewed May 28, 2026 Content v20260528
Track mode
server_script
Means
Server runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches JSON encode and decode: the syntax, APIs, and habits you need before advancing in PHP.

Teams ship JSON encode and decode on every PHP codebase—skipping it leaves gaps in debugging and code reviews.

You will apply JSON encode and decode in contexts like: LAMP/LEMP stacks, Laravel apps, WordPress themes/plugins, and shared hosting.

Write PHP in the editor and click Run on server—the dev runner executes your script and returns stdout/stderr (set LEARNING_RUNNER_ENABLED=true locally).

When you can explain the previous lesson's ideas without copying starter code.

APIs and modern front ends speak JSON. PHP converts arrays/objects to JSON strings and back with json_encode and json_decode.

Encoding

$data = ['ok' => true, 'items' => [1, 2]];
$json = json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);

Decoding

$parsed = json_decode($json, true); // associative array
// omit true for stdClass object

Common flags

JSON_THROW_ON_ERROR turns failures into exceptions. JSON_PRETTY_PRINT helps debugging. Always set Content-Type: application/json when returning JSON from real endpoints.

Important interview questions and answers

  1. Q: json_decode second parameter?
    A: true returns associative arrays; false (default) returns stdClass objects.
  2. Q: Why JSON_THROW_ON_ERROR?
    A: Silent false returns hide malformed input—exceptions fail fast in APIs.

Self-check

  1. What type do you get from json_decode($s, true)?
  2. When would you prefer objects over arrays for decoded JSON?

Pitfall: Enable JSON_THROW_ON_ERROR in APIs—silent false from json_decode hides malformed payloads.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • json_encode flags?
  • Invalid UTF-8 fix?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump