How to Read this json with PHP

Asked

Viewed 1,185 times

2

How do I read this JSON file with PHP.

I tried this way, but it doesn’t work.

<?php

    $json_str = '{
    "numero":"1000",
    "log": {
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    },
    "responsavel": {
        "nome":"Responsavel teste"
    }
}';

    $obj = json_decode($json_str);


    foreach ($obj as $objeto){

        echo "numero: ".$objeto->numero;

        foreach ($objeto as $item){

            echo "Mensagem: ".$item->message. " - ";
            echo "Nível: ".$item->level. "</br>";
        }

        foreach ($objeto as $responsavel){

            echo "NOME: ".$item->nome;

        }

    }


?>

2 answers

4


The json that presented has no arrays is all objects, so it makes no sense to use foreach to traverse.

To access the fields you are trying to access in the code you can do so:

echo "numero: ".$obj->numero;
echo "Mensagem: ".$obj->log->message. " - ";
echo "Nível: ".$obj->log->level. "</br>";
echo "NOME: ".$obj->responsavel->nome;

Example in Ideone

To be able to use the foreachs that has in the code, the json had to be like this:

[{
    "numero": "1000",
    "log": [{
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    }],
    "responsavel": [{
        "nome": "Responsavel teste"
    }]
}]

Notice how now you have the [ and ] each to indicate that it is an array of objects, which we can now traverse with foreach.

The code to traverse also has slightly adjusted that it had some errors:

$obj = json_decode($json_str);

foreach ($obj as $objeto){

    echo "numero: ".$objeto->numero;

    foreach ($objeto->log as $item){ //faltava aqui $objeto->log

        echo "Mensagem: ".$item->message. " - ";
        echo "Nível: ".$item->level. "</br>";
    }

    foreach ($objeto->responsavel as $responsavel){ //faltava aqui $objeto->responsavel

        echo "NOME: ".$responsavel->nome;

    }

}

See this latest version also on Ideone

1

By default the json_decode returns a stdClass and for your access it is not possible to use the foreach.

On the other hand you can do json_decode return an array, which in turn is eternal. In this particular file, it may not be worth it and use as a suggested object in that reply is simpler:

$json_str = '{
    "numero":"1000",
    "log": {
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    },
    "responsavel": {
        "nome":"Responsavel teste"
    }
}';

var_dump(json_decode($json_str, true);

Browser other questions tagged

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