Cassie Liu
Cassie Liu

Reputation: 195

How to access certain part of a nested JSON?

I'm trying to access the content of "text" in the following code. Actually I have asked almost the same question before and it was solved perfectly. How to access certain part of a JSON? However, when I use the same method on this JSON, it doesn't work.

$test = 
'{
    "username":"lon",
    "event":{
        "saved_response":"{\"parts\": [{\"text\": \"Passion for teaching means loving your job. Doing with all your heart. Teachers who are passionate can inspire pupils to love learning. Passionate teachers create an effective learning environment and increase learning potential of\\nstudents.\"}]}"
    },
    "event_source":"server"
}';

$jarray = json_decode($test, true);
$jevent = json_decode($jarray['event']['saved_response'], true);
var_dump($jevent);
echo $jevent['parts'][0]['text'];

The output is NULL and I don't know what to do. Can anyone help me with it? Thanks.

Upvotes: 0

Views: 47

Answers (1)

Red Bottle
Red Bottle

Reputation: 3080

The tried and tested json_decode(json_encode($test), true); Does the job for me. Cheers!

$test = 
'{
"username":"lon",
"event":{
    "saved_response":"{\"parts\": [{\"text\": \"Passion for teaching means loving your job. Doing with all your heart. Teachers who are passionate can inspire pupils to love learning. Passionate teachers create an effective learning environment and increase learning potential of\\nstudents.\"}]}"
},
"event_source":"server"
}';

$jarray = json_decode(json_encode($test), true);

$jarray = explode('"',$jarray);

print_r($jarray[14]);

Upvotes: 1

Related Questions