Problem with json slim framework

Asked

Viewed 401 times

1

I am making an api to do the integration of two different systems, the system sends me the following json:

cJson = [{"TESTE": "1"}]

I spent 3 days with a problem because I was not able to catch the json that the other system sent me via post with neither of these two methods below:

$dados = $request->getBody();

$dados = $request->getParsedBody();

I solved this problem and now I can get the json that the other system sends me with the seginte method:

$dados = (string) $resquest->getBody();

But this method just above returns me a string, and I need to transform it into an array or an object to insert it into the database. when I give an echo what is returned to me is just what I want to see right below:

echo $dados; 
resultado:   [{"TESTE": "1"}]

But when I use a json_decode it does not return anything to me returns null, example:

echo json_decode($dados);
resultado: null

Is it because it’s a string ? Is there any way I could fix this ? I’ve got the dice, but I can’t manipulate it into the bank...

2 answers

1


There is nothing wrong with converting the string to JSON. The problem is that you cannot display the result with echo( ), because the return of the function json_decode( ) is an array.

Experiment with print_r( ):

print_r(json_decode('[{"TESTE": "1"}]'));
resultado: Array ( [0] => stdClass Object ( [TESTE] => 1 ) )
  • I don’t know why but I used it like this: json_decode($data, true).

0

To transform from a json object to an array in Php you must use the syntax: echo json_decode($dados, TRUE); .
You have to pass the TRUE parameter to transform it into array.

To print the information you must perform a foreach to access the values and then you can use echo, if you are trying to print directly the array must use the command print_r.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.