How to consume JSON files in PHP in different ways?

Asked

Viewed 574 times

1

This topic differs from subjects such as: "How to consume JSON in PHP"; "Extract json value in php"; "Read string json on php" or "Recover JSON in PHP" Although there is co-relation on various subjects of the PHP language, and the JSON format, it addresses a specific problem, detailed and summarized.

In all the materials that deal with the subject of JSON in PHP, I can’t find one that cites the different ways to treat JSON. They treat json as if it is always expressed in the same way, which is not true in practice. So we always have an algorithm for each way it is expressed. There is a universal way to capture json data, or there is a specific way for the second case cited below?

A practical example would be that:

{  
   "friendslist":{  
      "friends":[  
         {  
            "steamid":"76561197960265731",
            "relationship":"friend",
            "friend_since":0
         },
         {  
            "steamid":"76561197960265738",
            "relationship":"friend",
            "friend_since":0
         },
         {  
            "steamid":"76561197960265740",
            "relationship":"friend",
            "friend_since":0
         },
         {  
            "steamid":"76561197960265747",
            "relationship":"friend",
            "friend_since":0
         }
      ]
   }
}

Surely it’s different from that:

[
   {
      "id":"578",
      "valor":"4.00",
      "CLIENTE":{
         "id":"492",
         "nome":"MARIA",
         "sobrenome":"Machado",
         "endereco":"Avenida das Am\u00e9ricas",
         "latitude":null,
         "longitude":null
      },
      "dataCompra":"DATA_AQUI",
      "PRODUTOS":[
         {
            "id":"14135",
            "codigoDeBarras":"7896015516260",
            "nome":"SONRIDOR",
            "detalhes":"500mg cx 60 comp",
            "categoria":"medicamento",
            "quantidade":"2",
            "precoUnitario":".10"
         }
      ],
      "FRANQUIA":{
         "id":"818",
         "nomeFantasia":null,
         "razaoSocial":null,
         "rede":{
            "id":"32",
            "nome":"Sapataria João"
         },
         "endereco":"Rua Acre",
         "latitude":"-22.899079",
         "longitude":"-43.181612"
      }
   }


]

The first case, until I find a way of reading

$steamid_player = "76561198112612121";
        $apikey = "APIKEY";


       $amg = file_get_contents("http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=$apikey&steamid=$steamid_player&relationship=friend");
        $decode = json_decode($amg, TRUE);

        foreach ($decode["friendslist"]["friends"][0] as $valor){

            $steamid = $valor["relationship"]->steamid;

            echo $steamid;
        }

But in the second case, I did not find practical examples. I can do at most a vardump.

  • 1

    "They treat JSON as if it were always expressed in the same way". It is always expressed in the same way. It is a standard to represent data and if you do not follow this pattern it will be an invalid JSON. The difference between the presented JSON is the data they represent. What do you mean by "universal way"? (Your PHP code does not work)

  • 1

    It’s... There are no "ways" to write the same format in another JSON structure. It might be interesting to take a look at the structure of objects in JS to better understand it. :)

  • [".... The difference between the presented JSON ..."] If there are differences in the presented JSON, JSON is not expressed in the same way, by definition. In the same way that there are no married singles. And yes, there are differences in the way that is "expressed" in both cases. The first case for example, passes an expressed data collection and a sub-collection afterwards. Both arrays, such that the first array represents an entire collection. In the second case, you pass 3 interdependent arrays, without expressing an antecedent collection. PHP is working normally in my environment.

  • To whom interested problem, answer script did not work on PHP5 but on 7.

2 answers

3


Actually the form of reading is similar to the first example you quoted. For example, when using json Decode I can access the array clients, products, etc. See an example applied to your situation.

<?php
//a opção true vai forçar o retorno da função como array associativo.
$conteudo = json_decode(file_get_contents('json.json'), true);

foreach($conteudo as $chave => $elementos){
        $cliente = isset($elementos['CLIENTE']) ? $elementos['CLIENTE'] : [];
        $produtos = isset($elementos['PRODUTOS']) ? $elementos['PRODUTOS'] : [];
        $franquia = isset($elementos['FRANQUIA']) ? $elementos['FRANQUIA'] : [];
        $rede = isset($elementos['FRANQUIA']['rede']) ? $elementos['FRANQUIA']['rede'] : [];

        var_dump($cliente);
        var_dump($produtos);
        var_dump($franquia);
        var_dump($rede);

        /**
        As propriedades de $cliente, $produtos, $franquia, etc, podem ser acessadas da seguinte
        maneira:
        $cliente['id'];
        Aqui você pode manipular os dados da forma que desejar (mandar persistir no banco, etc)
        */
        echo $cliente['id'];

        /*******************Exibição generica*******************************/
        exibir('CLIENTE', $cliente);
        exibir('PRODUTOS', $produtos);
        exibir('franquia', $franquia);
        exibir('rede', $rede);
}

function exibir($titulo, $elementos){
    echo '<br><br>' . $titulo;
    foreach($elementos as $chave => $elemento){
        if(is_array($elemento)){
            foreach($elemento as $chave => $valor){
                echo '<br>' . $chave . ' : ' . $valor;
            }
        }else{
            echo '<br>' . $chave . ' : ' . $elemento;
        }
    }
}

The id, value, and purchase properties can be accessed with instructions equivalent to echo $elementos['id'];

3

JSON is a notation-based form of object serialization used to describe object literals in javascript. Therefore, the notation should be flexible enough to reproduce any* type of object that can be described in that language.

Therefore, any mechanism that parses javascript or emits it needs to be flexible enough to emit any of the types of data that, composed, are used by javascript to build its objects.

The data types accepted by JSON are six:

  • the null object null;
  • the values boolean true and false;
  • floating point numbers of at least 64 bits;
  • 8-bit character strings, typically in UTF-8 encoding;
  • vectors, which are collections of values indexed by contiguous integers starting with 0; and
  • the so-called objects or dictionaries or hashes, which are collections of values indexed by strings.

A JSON parsing library needs to emit any of these six types; luckily, PHP has dynamic typing, so a single function can return any of the six types as needed.

That function is json_decode($json, true), as long as the second parameter is true so that the json_decode() return a Array instead of a object.

So, in your first example, to find the steamid from your third friend, you’d say $friends = json_decode($exemplo1, true); echo $friends["friendslist"][2]["steamid"];; to find the client’s last name in the second, you would say $sale = json_decode($exemplo2, true); echo $sale[0]["CLIENTE"]["sobrenome"];.

*: In fact, JSON is more restricted than the literals of javascript in the fact that it is not possible to include function literals in JSON, while literals of javascript may have it.

Browser other questions tagged

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