8

How do I remove ALL unnecessary whitespaces from a JSON String (in PHP)?

I assume that I need to use preg_replace with some clever regex in order to NOT touch the whitespaces that are part of the values.

A simple example would be:

Before: '{ "key": "value with whitespaces to maintain" }'

After: '{"key":"value with whitespaces to maintain"}'

Basically, I'm looking for a way to minify and pack the string as tight as possible without changing any data.

Geek Girl x0x0
  • 310
  • 1
  • 4
  • 15
  • One way would be to parse JSON and then use your own encoding implementation, it's not very difficult. – Cthulhu May 25 '14 at 20:38

3 Answers3

22

Sorry to state the obvious:

$before = '{ "key": "value with whitespaces to maintain" }';
$after  = json_encode(json_decode($before));

And it actually matches perfectly your example, see $after:

{"key":"value with whitespaces to maintain"}
hakre
  • 193,403
  • 52
  • 435
  • 836
  • What if `$before` is array or object? Nested function calling doesn't seem to work... – Lukas Feb 25 '23 at 12:40
  • @Lukas: Yes, given `$before` is not JSON Text but a PHP array or object value, there is no need to nest the function calls, as you only need to encode and not decode: `$after = json_encode($before);`. That's all, HTH. – hakre Mar 02 '23 at 13:12
5

A PHP preg_ solution:

preg_replace(
    '/\s(?=([^"]*"[^"]*")*[^"]*$)/', ''
    , '{ "key": "value a with whitespaces to maintain" }'
);

Inspired by: Regex to match all instances not inside quotes

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37
0

PHP =>

Syntax : ltrim(string,charlist)

Example :

`$str = '{ "name" : " Test Subject" }';`
`$obj = json_decode($str);`
`$obj->name = ltrim($obj->name);`
`var_dump($obj);`

JS/jQuery =>

Syntax : jQuery.trim( str )

Example :

`var obj={ "name" : " Test Subject" };`
`console.log(obj);`
`obj["name"]=obj.name.trim(); // OR // obj.name.replace(/^\s+/,"");`
`console.log(obj);`
AppCloudData
  • 61
  • 1
  • 4