Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indentation size with JSON_PRETTY_PRINT

Tags:

json

php

The php function json_encode() has an option to set indentation in the outputted json for a "pretty" version. This option is called: JSON_PRETTY_PRINT

A minor pet peeve is that this feature uses 4 spaces in said indentation.

Is there is a way to make it use 2 spaces instead of 4 or an efficient way to process the output to reduce the 4 spaces to 2 - without it breaking any of the json keys/values which may have spaces in them.

like image 259
Thomas Smart Avatar asked Apr 24 '15 02:04

Thomas Smart


1 Answers

Try this:

$data = ['some' => 'data'];
$json = preg_replace_callback ('/^ +/m', function ($m) {
  return str_repeat (' ', strlen ($m[0]) / 2);
}, json_encode ($data, JSON_PRETTY_PRINT));
like image 67
Cláudio Silva Avatar answered Oct 08 '22 23:10

Cláudio Silva