Problems with Json

Asked

Viewed 70 times

2

I have a file with requests in JSON format made to a server and my problem is that I know how to take these requests I mean those lines and handle in php

Example of how this File

{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}

In other words, each line is the answer given to the request I make.

Does anyone know how to do that

2 answers

3

To transform a json into an array, use the function json_decode(), then make a foreach and call the keys you want.

$original = '{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}
{"a":1,"b":2,"c":3,"d":4,"e":5}';

/*para pegar o ficheiro basta utilizar:*/
//$original = file_get_contents('ficheiro.json");
/* transforma em um json válido */
/* str_replace irá trocar '}' por '},' adicionando as vírgulas */
/* rtrim vai remover a última vírgula */
$json = '[' . rtrim(str_replace('}', '},', $original), ',') . ']';    

$arr = json_decode($json, true);

foreach ($arr as $item){
    echo $item['a'] . ' - ' .$item['b'] .' - '.$item['c'] .' - '.$item['d'] .' - '.$item['e'] .' - '. '<br>';
}

Ideone Exemplo

  • the problem is that the file being created is not controlled by me and in the end has no comma

  • @Testerapo I updated the response from rray with an alternative for you

  • 1

    Thanks for the @Maiconcarraro :D edition

2


I read @rray’s previous answer and although certain in JSON manipulation, I don’t think it answers the question in full. The best answer and according to the question: read from a "text file formatted in json" the solution is:

$handle = fopen("ficheiro.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $arr = json_decode($line, true);

        // se a linha lida resultar num JSON então temos um array
        if (is_array($arr)) {

            // Neste momento já tem os campos no array $arr
            // o código seguinte é apenas para mostrar o resultado
            // pelo que pode ser removido e substituido pela lógica desejada
            foreach ($arr as $k => $v) {
                echo "{$k}={$v} ";
            }
            echo "<br>";
        }
    }

    fclose($handle);
} else {
    echo "error ao abrir o ficheiro bla bla bla";
}

Note: it is important to say and according to the question how the file is produced with results of an external service it is important to validate with isset the name of the fields as any may not be present for some reason and as a consequence generate unwanted errors in their handling.

Browser other questions tagged

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