Table of Contents

PHP RFC: json_encode indentation

Introduction

Programs can serialize data to JSON using the json_encode function. The function is widely used for generating JSON responses or payload over HTTP. Currently, it's not possible to tell json_encode what indentation level (2 spaces, 4 spaces, etc.) should be used when using the JSON_PRETTY_PRINT option. When generating JSON files which can be used/read/edited by users, indentation starts to become a relevant topic.

Proposal

Introducing a 4th parameter, called indent. The type of the parameter is int and its default value is 4.

By default, an indentation of 4 spaces will be applied, just like the original json_encode behaviour with the JSON_PRETTY_PRINT option.

When the indent parameter is passed a different value, an indentation of N spaces will be applied.

$data = [
    'key' => 4,
    'other_key' => [2]
];
 
echo json_encode(['behavior' => 'default'], JSON_PRETTY_PRINT) . PHP_EOL;
echo json_encode($data, JSON_PRETTY_PRINT, 512, 2) . PHP_EOL;
 
?>
{
    "behavior": "default"
}
{
  "key": 4,
  "other_key": [
    2
  ]
}

Backward Incompatible Changes

The only breaking change this could cause is when programs are already passing a fourth parameter by accident.

Proposed PHP Version(s)

Unaffected PHP Functionality

Normal usage (as opposed to what is described in BIC) of the json_encode function will not be affected, as the default of 4 spaces will still be in effect.

Patches and Tests

Tests are written with the RFC

Vote

Voting opened on 2022-07-04 and closes on 2022-07-18.

Add support for changing the JSON indentation amount?
Real name Yes No
aaronjunker (aaronjunker)  
alec (alec)  
asgrim (asgrim)  
ashnazg (ashnazg)  
bmajdak (bmajdak)  
bukka (bukka)  
dharman (dharman)  
didou (didou)  
galvao (galvao)  
geekcom (geekcom)  
heiglandreas (heiglandreas)  
kalle (kalle)  
kguest (kguest)  
levim (levim)  
lufei (lufei)  
marandall (marandall)  
mbeccati (mbeccati)  
nicolasgrekas (nicolasgrekas)  
ocramius (ocramius)  
reywob (reywob)  
salathe (salathe)  
santiagolizardo (santiagolizardo)  
seld (seld)  
svpernova09 (svpernova09)  
timwolla (timwolla)  
trowski (trowski)  
twosee (twosee)  
weierophinney (weierophinney)  
Final result: 7 21
This poll has been closed.