Problems with Json

2

I have a file with JSON-formatted requests made to a server and my problem is that I know how I can get these requests on those lines and deal with php

Example of how the File is

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

That is, each line is the answer given to the request I make.

Someone knows how I can do this

    
asked by anonymous 27.06.2015 / 19:45

2 answers

2

I read the previous response from @rray and although it is right on handling JSON, I think it does not answer 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 because some may not be present for some reason and consequently generate errors unwanted in their manipulation.

    
28.06.2015 / 15:21
3

To transform a json into an array, use the json_decode () function, then do 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 Example

    
27.06.2015 / 20:04