json to html table in phpjavascript - Stack Overflow

i have a json file like this:{publicationDate: "28-02-2014",contracted: "Servicash - E

i have a json file like this:

{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 €",
signingDate: "28-02-2014"
},

i need to show it in a table like this:

<table>
            <tr>
                <td><strong>Data de publicação</strong></td>
                <td><strong>Empresa Contratada</strong></td>
                <td><strong>Empresa que Contratou</strong></td>
                <td><strong>ID</strong></td>
                <td><strong>Objecto adquirido</strong></td>
                <td><strong>Preço Contratual</strong></td>
                <td><strong>Data do Contrato</strong></td>
            </tr>
</table>

how i do it in PHP or javascript?

thank you very much people ;)

i have a json file like this:

{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 €",
signingDate: "28-02-2014"
},

i need to show it in a table like this:

<table>
            <tr>
                <td><strong>Data de publicação</strong></td>
                <td><strong>Empresa Contratada</strong></td>
                <td><strong>Empresa que Contratou</strong></td>
                <td><strong>ID</strong></td>
                <td><strong>Objecto adquirido</strong></td>
                <td><strong>Preço Contratual</strong></td>
                <td><strong>Data do Contrato</strong></td>
            </tr>
</table>

how i do it in PHP or javascript?

thank you very much people ;)

Share Improve this question asked Mar 1, 2014 at 19:42 user3332475user3332475 551 gold badge2 silver badges10 bronze badges 11
  • it's as an object you provided not json. – Suman Bogati Commented Mar 1, 2014 at 19:43
  • is a file like this:base.gov.pt/base2/rest/contratos?&sort(-publicationDate) – user3332475 Commented Mar 1, 2014 at 19:46
  • the content on file you provide is json indeed. – Suman Bogati Commented Mar 1, 2014 at 19:47
  • you can help me to show it on table? thank you – user3332475 Commented Mar 1, 2014 at 19:48
  • Do you want to show value of object into td something like "28-02-2014", "Servicash - Equipamentos Electrónicos, Lda.", "Banco de Portugal", please make me correct if i am wrong. – Suman Bogati Commented Mar 1, 2014 at 19:50
 |  Show 6 more ments

4 Answers 4

Reset to default 1

Here is how you can do it in PHP:

$json=file_get_contents("http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)");
$data =  json_decode($json);

//var_dump($data);
echo "<table>
           <tr>
                <td><strong>Data de publicação</strong></td>
                <td><strong>Empresa Contratada</strong></td>
                <td><strong>Empresa que Contratou</strong></td>
                <td><strong>ID</strong></td>
                <td><strong>Objecto adquirido</strong></td>
                <td><strong>Preço Contratual</strong></td>
                <td><strong>Data do Contrato</strong></td>
            </tr>";

foreach($data as $object):?>

           <tr>
                <td><strong><?php echo $object->{'publicationDate'}?></strong></td>
                <td><strong><?php echo $object->{'contracted'}?></strong></td>
                <td><strong><?php echo $object->{'contracting'}?></strong></td>
                <td><strong><?php echo $object->{'id'}?></strong></td>
                <td><strong><?php echo $object->{'objectBriefDescription'}?></strong></td>
                <td><strong><?php echo $object->{'initialContractualPrice'}?></strong></td>
                <td><strong><?php echo $object->{'signingDate'}?></strong></td>
            </tr>

<?php endforeach;
      echo "</table>";
?>

DEMO

Here is a JSFiddle that shows how to print the data in your object:

http://jsfiddle/4PVr5/1/

And the code:

HTML

<table id="table">
    <tr>

    </tr>
</table>

JAVASCRIPT

var object = {
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014"
};
for (var prop in object) {
      // important check that this is objects own property 
      // not from prototype prop inherited
      if(object.hasOwnProperty(prop)){
          var td = document.createElement("td");
          var strong = document.createElement("strong");
          var text = document.createTextNode(prop + " - " + object[prop]);
          strong.appendChild(text);
          td.appendChild(strong);
          document.getElementById("table").appendChild(td);
      }
   }

EDIT UPDATE TO angus_thermopylae:

I have updated the JSFiddle to show the concept: http://jsfiddle/4PVr5/12/

Then you can have as many properties on the object you want but only print the ones you defined and in the order you defined. You just add a text string and then you got another print.

EDIT UPDATE: I updated the code to follow the table headers. Now it adds them directly and also handles objects with too few properties.

HTML

<table id="table">
    <thead>
        <th id="publicationDate"></th>
        <th id="contracted"></th>
        <th id="contracting"></th>
        <th id="id"></th>
        <th id="objectBriefDescription"></th>
        <th id="initialContractualPrice"></th>
        <th id="signingDate"></th>
    </thead>
    <tbody>

    </tbody>
</table>

JAVASCRIPT

var orderedObject = {
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014"
};

var unorderedObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014",
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
};

var toManyPropertiesObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014",
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    newProp: "ignored",
    newProp1: "ignored",
    newProp2: "ignored",
};


var toFewPropertiesObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
};

printObjectInTable(orderedObject, "table");
printObjectInTable(unorderedObject, "table");
printObjectInTable(toManyPropertiesObject, "table");
printObjectInTable(toFewPropertiesObject, "table");

function printObjectInTable(objectToIterate, tableID) {
    var thChildren = document.getElementById(tableID).getElementsByTagName("th"),
        childrenLength = thChildren.length,
        tr = document.createElement("tr");
    for (var i = 0; i < thChildren.length; i++) {
        var th = thChildren[i];
        // important check that this is objects own property 
        // not from prototype prop inherited
        var td = document.createElement("td");
        if (objectToIterate.hasOwnProperty(th.id)) {
            td.appendChild(document.createTextNode(objectToIterate[th.id]));
        }
        tr.appendChild(td);
    }
    document.getElementById(tableID).getElementsByTagName("tbody")[0].appendChild(tr);
}

A per-row conversion will work something like this (low level and not doing anything fancy):

//with jdata as the object below
{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 €",
signingDate: "28-02-2014"
}

function tablize(jdata) {
    var trow = "<tr>";
    trow += "<td>"+jdata.publicationData+"</td>";
    trow += "<td>"+jdata.contracted+"</td>";
    trow += "<td>"+jdata.contracting+"</td>";
    trow += "<td>"+jdata.id+"</td>";
    trow += "<td>"+jdata.objectBriefDescription+"</td>";
    trow += "<td>"+jdata.initialContractualPrice+"</td>";
    trow += "<td>"+jdata.signingDate+"</td>";
    trow += "</tr>"
    return trow;
}

Now your issue is getting it in the table. Assuming you have the ability to adjust (slightly) the table structure, I would remend setting up your table like so:

<table>
    <thead>
        <tr>
            <th><strong>Data de publicação</strong></th>
            <th><strong>Empresa Contratada</strong></th>
            <th><strong>Empresa que Contratou</strong></th>
            <th><strong>ID</strong></th>
            <th><strong>Objecto adquirido</strong></th>
            <th><strong>Preço Contratual</strong></th>
            <th><strong>Data do Contrato</strong></th>
        </tr>
    </thead>
    <tbody id="cdata"></tbody>
</table>

Then, you just need a function to either iterate through all the data and add the accumulated rows, or append the newly created row to the element:

Assuming you'll get this data as an array:

function fillTable(contractarray) {
    var tblrows = "";
    if (contractarray) {
        for (var i=0;i<contractarray.length;i++) {
            tblrows += tablize(contractarray[i]);
        }
    }
    //appropriate method to set the table body--using jQuery for brevity
    $("#cdata").html(tblrows);
}

If you don't have the ability to adjust the table html, then you'll have to "find" the table in the DOM structure another way and either recreate the entire thing (headers included) or adjust it by clearing/adding rows appropriately.

Either way, the tablize(jdata) function will work, and the second function will need to be adjusted accordingly.

To pull it altogether (with the url that the requestor supplied:

var dataurl = "http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)";

$.getJSON(dataurl, function(data) { tablize(data)});

That kicks off the request, passes the data to the tablize() function, and fills the rows. A small (but good) side effect is that if no data is returned, the table empties, showing that we got nothing back.

Accoding to your answer on ment, you are using

$('table#tbl TBODY').append(

for append the data into table,

But you should use

$('table#tbl').append(

Other code is fine

Also you have to run your code into web server.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745212466a4616923.html

相关推荐

  • json to html table in phpjavascript - Stack Overflow

    i have a json file like this:{publicationDate: "28-02-2014",contracted: "Servicash - E

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信