How to consume JSON files in PHP in different ways?

1
  

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

In all materials that deal with the subject of JSON in PHP, I find none that cite the different ways of treating JSON. They treat json as if it were always expressed in the same way, which is not true in practice. So we always have an algorithm for every way it is expressed. Is there a universal way of capturing the json data, or is there a specific way for the second case quoted below?

A practical example would be that this:

{  
   "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
         }
      ]
   }
}

Certainly it's different than 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 to read

$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 found no practical examples. I can do at most a vardump.

    
asked by anonymous 01.07.2017 / 00:08

2 answers

3

Actually the form of reading is similar to the first example you mentioned. 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 properties id, value, datecompra can be accessed with instructions equivalent to echo $elementos['id'];

    
01.07.2017 / 01:57
3

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

So, any mechanism that parses javascript or that issues it needs to be flexible enough to issue any of the data types that, compound, are used by javascript to build your objects.

The data types supported by JSON are six:

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

A library that analyzes JSON needs to issue any of these six types; Fortunately, PHP has dynamic typing, so a single function can return any of the six types as needed.

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

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

*: In fact, JSON is more restricted than javascript literals in that it can not include function literals in JSON, whereas javascript literals can have it.

    
01.07.2017 / 02:11