Handling JSON in PHP

Asked

Viewed 40 times

2

I have a function that consumes a REST API and that the sponse me returns a JSON file with a lot of data. But I am error in converting this data to be able to manipulate it in a way but easy.

Here’s a small example of a similar error:

<?php
  $json = '{"dados"{"nome":"marcos"}}';
  $data = json_encode($json);
  $dados = json_decode($data,true);
  echo $dados["dados"]["nome"];
?>

Where the mistake is this:

inserir a descrição da imagem aqui

<?php
  $json = '{"dados"{"nome":"marcos"}}';
  $data = json_encode($json);
  $dados = json_decode($data);
  echo $dados->dados;
?>

In this the error is similar:

inserir a descrição da imagem aqui

Any tips on how to solve? Similar examples in the stack always show to use the assosiative array with the json_decode($data, true) but keeps generating the same mistake.

1 answer

2


First, the JSON is wrong, missed put : between the "data" key and its value:

$json = '{"dados": {"nome":"marcos"}}';
                 ^ aqui

Second, if you have a string and want to transform it into an array, use json_decode directly. In this case it makes no sense to use json_encode and then use json_decode:

$json = '{"dados": {"nome":"marcos"}}';
$dados = json_decode($json, true);
echo $dados["dados"]["nome"]; // marcos

Or, if you want an object instead of an associative array:

$json = '{"dados": {"nome":"marcos"}}';
$dados = json_decode($json);
echo $dados->dados->nome; // marcos

Just to clarify: if you have a string and want to transform into an array/object, use json_decode. If you want to do otherwise (turn the array/object into a string), then you use json_encode.

As the code starts with a string, then use json_encode it was not necessary, just use json_decode.

  • The problem with using json_encode in a return already in JSON. Removing json_encode it worked.

Browser other questions tagged

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