Alperen Özdemir Alperen Özdemir - 1 year ago 113
JSON Question

Parsing JSON With changeable key

I try to parse json variables with php codes. Problem is some of array keys contain changeable values for each iteration. By the way this is not a duplicate question, there is nothing like json parsing with changeable variables. Here is my json example and php codes and also output;

"filename":"Rock Ballads The Best Of 70-90's",
"audio track in mp3 (54.54MB)":"http:\/\/\/str\/wlqcjv8246\/Rock+Ballads+The+Best+Of+70-90%26%23039%3Bs%28p%29.mp3",
"360p video in mp4 (80.04MB)":"http:\/\/\/str\/wlqcjyfc33\/Rock+Ballads+The+Best+Of+70-90%26%23039%3Bs%28480p%29.mp4",
"240p video in mp4 (76.55MB)":"http:\/\/\/str\/wlqck18b72\/Rock+Ballads+The+Best+Of+70-90%26%23039%3Bs%28240p%29.mp4",
"144p video in mp4 (71.09MB)":"http:\/\/\/str\/wlqck4e410\/Rock+Ballads+The+Best+Of+70-90%26%23039%3Bs%28144p%29.mp4"

and this is the php code that I use;

$decodeProcess = json_decode($output,true);
echo ($decodeProcess['filename']);
echo ($decodeProcess['icon']);
echo ($decodeProcess['streaming']['audio track in mp3 (54.54MB)']);


In this case filename and icon works well but "audio track in mp3 (54.54MB)" or "144p video in mp4 (71.09MB)" is problem for me to parse because everytime the file size changes. What can I do?

Answer Source

Have you considered running a simple mapping operation on the data structure to get it into a more workable form (basically dropping file size information from keys)?

That might look like:

    $decodeProcess = json_decode($output,true);
    // array of prefix matches that will be used as as substitution keys
    $key_replacements = [
        'audio' => 'audio',
        '360p video' => 'video_360p',
        '240p video' => 'video_240p',
        '144p video' => 'video_144p'
    foreach($decodeProcess['streaming'] as $key => $value) {
        foreach ($key_replacements as $prefix => $replacement) {
            if (strpos($key, $prefix) === 0) {
                $decodeProcess['streaming'][$replacement] = $value;

    echo ($decodeProcess['filename']);
    echo ($decodeProcess['icon']);
    echo ($decodeProcess['streaming']['audio']);
    echo ($decodeProcess['streaming']['video_360p']);

Of course you might want to then encapsulate the overall JSON deserialization and key mapping functionality into its own function or class method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download