Forum: PC-Programmierung php json decoding


von tom (Gast)


Lesenswert?

I tried to parse a JSON file using PHP. But I am stuck now.
This is my JSON file
1
{
2
        "devices": {},
3
        "rules": {},
4
        "gui": {},
5
        "settings": {
6
                "log-level": 6,
7
                "pid-file": "..",
8
                "log-file": "..",
9
                "webserver-enable": 1,
10
                "webserver-root": "..",
11
                "webserver-http-port": 5001,
12
                "webserver-cache": 1
13
        },
14
        "hardware": {
15
                "433gpio": {
16
                        "sender": 0,
17
                        "receiver": 1
18
                }
19
        },
20
        "registry": {
21
                "..": {
22
                        "version": {
23
                                "current": "7.0"
24
                        }
25
                }
26
        }
27
}
And this is my PHP so far:
1
<?php
2
 
3
$json = "config.json";
4
 
5
$jsonIterator = new RecursiveIteratorIterator(
6
 
7
    new RecursiveArrayIterator(json_decode($json, TRUE)),
8
 
9
    RecursiveIteratorIterator::SELF_FIRST);
10
 
11
 
12
 
13
foreach ($jsonIterator as $key => $val) {
14
 
15
    if(is_array($val)) {
16
 
17
        echo "$key:\n";
18
 
19
    } else {
20
 
21
        echo "$key => $val\n";
22
 
23
    }
24
 
25
}
26
 
27
?>

But it didn’t work? So I appreciate an example for this.

von TestX (Gast)


Lesenswert?

You don't need the recursiveIterator. Json_decode will return an 
associative array (second parameter set true).

Please refer to the documentation on php.net

von Sushi (Gast)


Lesenswert?

I think you need to read the file first before you can parse it.
1
<?php
2
3
$json = "config.json";
4
$data = file_get_contents($json);
5
$parsed = json_decode($data, TRUE);
6
7
echo "<plaintext>";
8
print_r($parsed);
(Code not tested)

Bitte melde dich an um einen Beitrag zu schreiben. Anmeldung ist kostenlos und dauert nur eine Minute.
Bestehender Account
Schon ein Account bei Google/GoogleMail? Keine Anmeldung erforderlich!
Mit Google-Account einloggen
Noch kein Account? Hier anmelden.