Doubt about json_encode and json_decode

Asked

Viewed 4,702 times

5

When and how we should use json_encode and json_decode? What are they for?

2 answers

7

Whenever you need to send data between server and client, or an API, or write data in a structured format you can use the JSON format.

JSON is a string, and to work this data in PHP you need to interpret it, for that you use the json_decode.

Whenever you need to transform data into a JSON text string to send or save you can use json_encode.

To convert JSON string:

$string_json = '["item1","item2"]';
$array = json_decode($string_json);
var_dump($array); // dá uma array:

array(2) {
  [0]=>
  string(5) "item1"
  [1]=>
  string(5) "item2"
}

To convert to JSON string:

$array = array('item1', 'item2');
$string_json = json_encode($array);
echo $string_json; // dá uma string: '["item1","item2"]'
  • 1

    Thank you so much!! I am doing a course, and we arrived at this part but it wasn’t very clear to me. !! Thanks for the instruction!!!

  • you reversed the codes.

  • @HENRIQUELOBO haha :) Thank you. I edited and corrected.

2

JSON is only a structured file writing format, that is, it is an equivalent alternative to xml or csv.

Generally, the JSON format is used for information traffic between API’s restful, non-relational database, and even used within javascript programming.

By better exemplifying the uses of json, it is possible that I write the same information in various ways, examples:

JSON format

{
    [
        "nome": "João",
        "idade": 22
    ],
    [
        "nome": "José",
        "idade": 25
    ],
}

CSV format

Nome;Idade;
"João", 22
"José", 25

XML format

<pessoa>
    <nome>"João"</nome>
    <idade>22</idade>
</pessoa>
<pessoa>
    <nome>"José"</nome>
    <idade>25</idade>
</pessoa>

Have you noticed that despite the format they all manage to carry the same content? The only thing that defines what type to use is the need for application, and the decodes cited are only to collect this information and translate it to PHP.

Browser other questions tagged

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