Home > Net >  Load JSON File and print specific Parts
Load JSON File and print specific Parts

Time:11-16

im building a simple webpage for school. Sadly ive got several problem. Im using an Apache Webserver with XAMPP.

I got a JSON-File like:

{
    
"lose":[
{
    "Zustand":"geschlossen",
    "Losnummer":1,
    "Gewinnklasse":"A",
    "Preis":10
},

{
    "Zustand":"geschlossen",
    "Losnummer":2,
    "Gewinnklasse":"B",
    "Preis":20
},

This file is on my Webserver too. I want to load this file especially with XHTML Request and then want to print several parts of this JSON File into HTML/PHP Code. I watched a lot of youtube videos but i dont get a way that works for me. I managed to load the JSON-File via XHTML and im able to print it in HTML, but it is always the whole JSON in the so called "responseText" and this is basically a large String for me. Im fairly new in this stuff so sorry if i mess things up.

So TLDR: load JSON file in webpage, print single parts of it in several HTML div tags. Im allowed to use html,php,js.

CodePudding user response:

Something like this:

<?php 
$json = 
'
{
    "lose": [
    {
        "Zustand":"geschlossen",
        "Losnummer":1,
        "Gewinnklasse":"A",
        "Preis":10
    },
    {
        "Zustand":"geschlossen",
        "Losnummer":2,
        "Gewinnklasse":"B",
        "Preis":20
    }]
}
';

$arr = json_decode($json, true);
echo "<table border='1'>";
foreach($arr["lose"] as $single) {
    echo "<tr>";
    echo "<td>".$single['Zustand']."</td>";
    echo "<td>".$single['Losnummer']."</td>";
    echo "</tr>";
}
echo "</table>";

CodePudding user response:

In JS, you can use the built-in JSON.parse() method.

https://www.w3schools.com/Js/js_json_parse.asp

You can then access individual elements in that data structure as first class citizens.

Using your example, here's a minimum working example:

let dataString = ` 
{
    "lose":[
        {
            "Zustand":"geschlossen",
            "Losnummer":1,
            "Gewinnklasse":"A",
            "Preis":10
        },    
        {
            "Zustand":"geschlossen",
            "Losnummer":2,
            "Gewinnklasse":"B",
            "Preis":20
        }
    ]
}
`

let data = JSON.parse(dataString);


// If we log out data, it will simply print everything
console.log(data);

// This will access the first element of the array
console.log(data.lose[0]); 

// To iterate through the entire 'LOSE' array
data.lose.forEach(element => {
    // Since we're in the middle of the array, we can now access individual properties
    console.log(element.Zustand);
});
  • Related