iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JSON Reference

JSON reference. Two functions cover everything — flags do the heavy lifting.

Functions

FunctionReturns
json_encode($value, $flags = 0, $depth = 512)JSON string or false.
json_decode($json, $assoc = false, $depth = 512, $flags = 0)Mixed.
json_last_error() / json_last_error_msg()Last error / human-readable string.
JsonExceptionThrown if you pass JSON_THROW_ON_ERROR.
JsonSerializable interfaceClass can choose its own JSON shape via jsonSerialize().

Flags

FlagEffect
JSON_PRETTY_PRINTIndented output.
JSON_UNESCAPED_SLASHESDon't escape /.
JSON_UNESCAPED_UNICODEKeep Unicode literal.
JSON_THROW_ON_ERRORThrow JsonException instead of returning false.
JSON_FORCE_OBJECTEmit {} for empty arrays.
JSON_NUMERIC_CHECKStrings that look numeric become numbers.
JSON_PARTIAL_OUTPUT_ON_ERRORDon't fail on unserialisable values.
JSON_OBJECT_AS_ARRAY(decode) Same as passing $assoc = true.

Type mapping

JSONPHP (encode)PHP (decode w/ $assoc = true)
objectassoc arrayassoc array
arrayindexed arrayindexed array
stringstringstring
numberint / floatint / float
true / falseboolbool
nullnullnull

Common pitfalls

  • Empty PHP array [] encodes to []; if you wanted {}, use (object) [] or JSON_FORCE_OBJECT.
  • Float precision — json_encode(0.1 + 0.2) emits 0.30000000000000004.
  • Resources, closures, and PDOStatement can't be encoded.
  • Decoding deep structures may hit $depth — bump it for big payloads.
Tip: Always pass JSON_THROW_ON_ERROR. Old code that checks === false after a JSON call almost always forgets to check, which is exactly the bug that bites in production.

Example

Example
<?php
echo json_encode(['ok' => true]), PHP_EOL;
print_r(json_decode('{"ok":true}', true));
Try it Yourself »

Exercise

Recommended flag for safer error handling.

json_encode($x, JSON _)

Test yourself

Q1. For decoding into associative arrays pass…
Q2. Empty array encodes to {} only with…
Q3. JsonSerializable lets you…

Discussion

Loading…