0

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.

2
  • Did you try to use 'false' in your json_decode method? Commented Dec 2, 2021 at 15:20
  • 1
    Well, if you need to decode it twice on backend means obviously that you've serialized it one time in excess on frontend Commented Dec 2, 2021 at 15:21

1 Answer 1

1

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"
}
*/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.