0

how to remove whitespace on beginning of a JSON string.

example:

{ "name" : " Test Subject" }

to

{ "name" : "Test Subject" }

the space before 'Test' to be removed

emilkitua
  • 95
  • 2
  • 3
  • 12

1 Answers1

2

The solution using json_decode and trim functions:

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

$str = json_encode($obj);  // back to JSON string
var_dump($str);

The output:

string(23) "{"name":"Test Subject"}"
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105