Doubts regarding the use of json_encode and json_decode

4

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

    
asked by anonymous 22.06.2017 / 17:28

2 answers

5

When you need to send data between the 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 with this data in PHP you need to interpret them, for this you use json_decode .

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

To convert from string JSON:

$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"]'
    
22.06.2017 / 17:30
2

JSON is just a structured format for writing files, that is, it is an equivalent alternative to xml or csv .

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

For a better example of the uses of json, it is possible for me to write the same information in several 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 can carry the same content? The only thing that defines what type to use is the need for application, and the decodes are just to collect this information and translate it to PHP.

    
22.06.2017 / 19:06