0

i want to create a json viewer for an api that converts a json to a list of table, can someone point me how its done? i know its possible but i don’t know how to do it.

e.g.

{"name":diana,
"age":12,
"gender":"male"}

to:

<table>
  <tr>
   <td>name:</td><td>diana</td>
  </tr>
  <tr>
   <td>age:</td><td>12</td>
  </tr>
  <tr>
   <td>gender:</td><td>male</td>
  </tr>
</table>

if something is not clear please let me know :) i forgot to mention that i will be working for a nested json. m(_ _)m

Viscocent
  • 2,024
  • 2
  • 19
  • 26
  • 1
    What have you tried yet? Have a look into recursion. JSON can be nested indefinitely deep, so your viewer has to account for that. And make sure your table layout allows this nesting. – Till Helge Apr 17 '13 at 06:30
  • Agreed with @TillHelgeHelwig all answers provided are for one level, but if you check simply expedia api for example,its provide you response in json format multi level. – rahularyansharma Apr 17 '13 at 06:38
  • @TillHelgeHelwig yes you are right, its my fault for not emphasizing the size of the array as i only made a simple sample for my question but in reality i have to work on deep nested JSON. – Viscocent Apr 17 '13 at 06:41

7 Answers7

3

Use json_decode to parse json, then iterate over the result...

echo "<table>\n";
$data = json_decode($json, true);
foreach($data as $key=>$value) echo "<tr><td>{$key}:</td><td>{$value}</td></tr>\n";
echo "</table>\n";

Note that this will work only for such "simple" json objects as you gave in example... If theres multi-level nesting, this won't be enough. You will have to check the type of $value and decide how to print it at any level of nesting...

Also note, that json string can also be not an object at all. It can also be a primitive type.

Ultimately, you either have a multidimensional array, or an object (if you ommit the second parameter from json_decode call). From that point on, the 'goal' changes from pretty-print a json object into pretty-print a php variable. There are plenty of solutions for that.

poncha
  • 7,726
  • 2
  • 34
  • 38
  • 1
    I would add if-check for the cycle, array type conversion for the json_decode result and escaping for the value – Artjom Kurapov Apr 17 '13 at 06:31
  • You should note that if you don't pass `true` as the second argument, it returns objects, rather than a multi-dimensional array. So either you'd need `$data as $obj ... $obj->name...` or you'd need `json_decode($json, true);` – Norguard Apr 17 '13 at 06:32
  • @Sohail no, it does not, and so does the note in the end of the answer state ;) Well, actually, it won't fail - it will just output the word "Array" as the value. – poncha Apr 17 '13 at 06:37
  • @poncha what do i do if there is multi-level-nesting? donnu if this work but im thinking of making your code into a function and if a variable is an array then it will call(recursively) that function again. do you have better ideas of what should i do? – Viscocent Apr 17 '13 at 06:53
  • 1
    thanks for your input @poncha i got what you meant :). i made a function(can recursively call itself if a value is an array) that has no json_decode and called it within your code. – Viscocent Apr 17 '13 at 07:53
3

Try this code

 $arr = json_decode($jsonstring);

<table>
<?php foreach($arr as $key=>$val){ ?>
  <tr>
   <td><?php echo $key?>:</td><td><?php echo $val;?></td>
  </tr>
<?php }?>

<table>
Praveen kalal
  • 2,148
  • 4
  • 19
  • 33
2

Here is pretty simple way to do it..

$str = '{"name":"diana",
"age":12,
"gender":"male"}';
$str = json_decode($str, TRUE);

echo '
<table>
  <tr>
   <td>name:</td><td>'.$str['name'].'</td>
  </tr>
  <tr>
   <td>age:</td><td>'.$str['age'].'</td>
  </tr>
  <tr>
   <td>gender:</td><td>'.$str['gender'].'</td>
  </tr>
<table>';

Json_decode converts your JSON array to php array with set second param to TRUE its assoc. array.

Svetoslav
  • 4,686
  • 2
  • 28
  • 43
  • @Sohail you are wrong.. Its the same method as other responds but in my case I don't use my key as output in the table, only for picking the correct value from the array. – Svetoslav Apr 17 '13 at 06:37
1

Check out this one. hope it will be helpful.

SohailRajput
  • 629
  • 1
  • 7
  • 18
  • interesting but i need to have a php version, though i might take a peek if it performs well better than the PHP version – Viscocent Apr 17 '13 at 06:46
1

Try this one...

$str = '{ "name": "diana",
"age": 12,
"gender": "male"}';
$dstr = json_decode($str);

echo '
<table>
  <tr>
   <td>name:</td><td>'.$dstr->name.'</td>
  </tr>
  <tr>
   <td>age:</td><td>'.$dstr->age.'</td>
  </tr>
  <tr>
   <td>gender:</td><td>'.$dstr->gender.'</td>
  </tr>
<table>';
Zinal Shah
  • 431
  • 2
  • 12
0

heres my full code(working) -- and kudos to @poncha

<style type="text/css">
    table{border-collapse: collapse;}
    td{border:1px solid #aaa;}
    .array{border-right:0px;}
</style>

<?php
$json_raw = '{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}';

function JSON_to_HTML($json){
    echo "<table>";
    foreach($json as $key=>$value){
        if($value):
            if(is_array($value)):
                echo "<tr><td class='array'>{$key}:</td><td>";
                JSON_to_HTML($value);
                echo "</td></tr>";
            else:
                if(preg_match('/.png|.gif|.jpg.|jpeg/', $value)):
                    echo "<tr><td>{$key}:</td><td class='italic'>{$value}</td></tr>";   
                else:
                    echo "<tr><td>{$key}:</td><td>{$value}</td></tr>";  
                endif;
            endif;  
        else:
            echo "<tr><td class='field-grey'>{$key}:</td><td class='field-empty'><span class='null'>null</span></td></tr>";
        endif;
    }
    echo "</table>";
}

echo "<table class='outer'>";
$data = json_decode($json_raw, true);
foreach($data as $key=>$value){
    if($value):
        if(is_array($value)):
            echo "<tr><td class='array'>{$key}:</td><td>";
            JSON_to_HTML($value);
            echo "</td></tr>";
        else: echo "<tr><td>{$key}:</td><td>{$value}</td></tr>";        
        endif;
    else: echo "<tr><td>{$key}:</td><td class='field-empty'><span class='null'>null</span></td></tr>"; endif;
} 
echo "</table>";
?>
Viscocent
  • 2,024
  • 2
  • 19
  • 26
0
$s = '{"access": {"token": {"issued_at": "2008-08-16T14:10:31.309353", "expires": "2008-08-17T14:10:31Z", "id": "MIICQgYJKoZIhvcNAQcCoIICMzCC"}, "serviceCatalog": [], "user": {"username": "ajay", "roles_links": [], "id": "96d10efe549", "roles": [], "name": "ajay"}}}';

$crl = 0;
$ss = false;
echo "<pre>";
for($c=0; $c<strlen($s); $c++)
{
    if ( $s[$c] == '}' || $s[$c] == ']' )
    {
        $crl--;
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
    if ( $s[$c] == '"' && ($s[$c-1] == ',' || $s[$c-2] == ',') )
    {
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
    if ( $s[$c] == '"' && !$ss )
    {
        if ( $s[$c-1] == ':' || $s[$c-2] == ':' )
            echo '<span style="color:#0000ff;">';
        else
            echo '<span style="color:#ff0000;">';
    }
    echo $s[$c];
    if ( $s[$c] == '"' && $ss )
        echo '</span>';
    if ( $s[$c] == '"' )
          $ss = !$ss;
    if ( $s[$c] == '{' || $s[$c] == '[' )
    {
        $crl++;
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
}
echo $s[$c];
J Ajay
  • 319
  • 3
  • 3