RuneRasset
RuneRasset

Reputation: 141

Get array of strings from json with json_decode

Seems like an easy thing, but I am not getting the expected data. I want to send an array of strings to my backend and then iterate/do stuff with them.

In the frontend I have:

var jsonArray = ["String1", "String2"]
await newFile(JSON.stringify(jsonArray));

In my controller, I have:

$requestData = json_decode($request->getContent(), true); 
$this->logger->info("File request data is ", [ $requestData ]);

My logger outputs:

File request data is ["[\"String1\",\"String2\"]"]

Which is not an array, but a string.

If I do it inside of php with

$txt = ["Test", "Test2"];
$json = json_encode($txt, true);

print_r(json_decode($json));

The output would be an array. Where am I going wrong or what am I missing? Having the true option in json_decode should return me my array.

Upvotes: 0

Views: 173

Answers (1)

jspit
jspit

Reputation: 7703

This

["Test", "Test2"]

is an Array, and this

"[\"String1\",\"String2\"]"

is a string. json_decode() need a string as parameter.

$jsonString = "[\"String1\",\"String2\"]";
$array = json_decode($jsonString, true);

var_dump($array);

/*
array(2) {
  [0]=>
  string(7) "String1"
  [1]=>
  string(7) "String2"
}
*/

Upvotes: 1

Related Questions