JSON Basics

View saved

Encode an array

json_encode turns PHP values into JSON text.

<?php
$user = ["name" => "Ada", "lessons" => 4];
echo json_encode($user), "\n";

Decode JSON text

json_decode can return objects or associative arrays.

$json = '{"name":"Ada","lessons":4}';
$data = json_decode($json, true);
echo $data["name"], "\n";

Check for errors

Validate decoding before trusting the result.

$data = json_decode("not-json", true);
if (json_last_error() !== JSON_ERROR_NONE) {
  echo "Invalid JSON\n";
}

JSON habits

  • Set Content-Type: application/json for API responses
  • Prefer associative arrays (true flag) while learning
  • Escape and validate data before encoding user content into larger documents
  • Combine with file_get_contents for simple file-backed storage

Comments

One comment per signed-in account. Comments are saved with this page’s URL.