Skip to content
PHPBot

PHP JSON Handling: Decode, Encode and Best Practices

PHP provides native functions to convert between JSON strings and PHP data types. To handle these conversions reliably, developers must manage structural output (objects vs. arrays), protect numeric precision for large identifiers, and implement modern exception-based error handling.

Handling Large Integers and Precision Loss

JSON numbers can exceed the maximum integer range of the current PHP platform. If a large integer is decoded without specific flags, it may be converted to a float, resulting in a loss of precision.

To prevent this, use the JSON_BIGINT_AS_STRING flag. This instructs json_decode() to treat large integers as strings instead of attempting to convert them to numeric types. Note that this flag is intended for integers that fall outside the platform's integer range, rather than every numeric ID.

<?php
$json = '{"large_id": 12345678901234567890}';

// Precision loss: converted to float
$lossy = json_decode($json);
var_dump($lossy->large_id);

// Precision preserved: converted to string
$safe = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
var_dump($safe['large_id']);
?>

Decoding: Objects vs. Associative Arrays

The json_decode() function converts a JSON encoded string into a PHP value. By default, JSON objects are returned as stdClass objects.

To return them as associative arrays, set the second parameter, $associative, to true. When $associative is null (the default), the behavior depends on whether the JSON_OBJECT_AS_ARRAY flag is set in the $flags parameter.

<?php
$json = '{"id": 101, "name": "Item"}';

// Returns stdClass object
$obj = json_decode($json);
var_dump($obj->name);

// Returns associative array
$arr = json_decode($json, true);
var_dump($arr['name']);
?>

Encoding PHP Values

The json_encode() function converts PHP values into a JSON string. If the input is an array or an object, it is serialized recursively.

When encoding an array, its structure determines the JSON output. Sequential arrays (starting from index 0) are encoded as JSON arrays, while non-sequential or associative arrays are encoded as JSON objects.

<?php
$data = ['a' => 1, 'b' => 2];
$json = json_encode($data);
// Output: {"a":1,"b":2}

$list = [1, 2, 3];
$json_list = json_encode($list);
// Output: [1,2,3]
?>

Robust Error Management

Standard JSON functions return null or false upon failure. For more robust error management in PHP 7.3+, use the JSON_THROW_ON_ERROR flag. This causes the functions to throw a JsonException instead of failing silently, allowing for cleaner try-catch implementations.

<?php
try {
    $invalid_json = '{"key": "missing_bracket"';
    $result = json_decode($invalid_json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "Error: " . $e->getMessage();
}
?>

JSON Workflow Example

This example demonstrates a full cycle: decoding a large integer safely as a string, manipulating the data, and re-encoding it. Note that re-encoding a string-preserved integer will result in a quoted JSON string, not a numeric token.

<?php
// 1. Input JSON with a large ID (exceeding 64-bit integer range)
$input_json = '{"user_id": 12345678901234567890, "active": true}';

try {
    // 2. Decode with precision protection and associative array format
    $data = json_decode($input_json, true, 512, JSON_BIGINT_AS_STRING | JSON_THROW_ON_ERROR);
    
    // 3. Modify data
    $data['processed'] = true;
    
    // 4. Re-encode
    $output_json = json_encode($data, JSON_THROW_ON_ERROR);
    
    echo "Original: " . $input_json . PHP_EOL;
    echo "Processed: " . $output_json . PHP_EOL;
    
    // Verification of types
    var_dump($data['user_id']); // string(20) "12345678901234567890"
    
} catch (JsonException $e) {
    echo "JSON Error: " . $e->getMessage();
}
?>

Summary of Best Practices

When working with JSON in PHP, follow these rules to ensure data integrity:

1. Use JSON_BIGINT_AS_STRING when decoding IDs that may exceed integer limits.

2. Use true as the second argument to json_decode if you prefer working with associative arrays over stdClass objects.

3. Always use JSON_THROW_ON_ERROR (PHP 7.3+) to catch syntax or encoding errors via exceptions.

4. Be aware that re-encoding a large integer that was decoded as a string will result in a quoted string in the final JSON output.

  • Verify large integer handling using JSON_BIGINT_AS_STRING.
  • Confirm associative array output by passing true to the second parameter of json_decode.
  • Implement JSON_THROW_ON_ERROR to handle JsonException for syntax errors.

PHPBot: Handle JSON by combining precision flags, structural preferences, and exception-based error management.