Ahmet Melih Başbuğ
Ahmet Melih Başbuğ

Reputation: 189

javascript load and use json data file

I need to load my data.json file and print "a"s name and age to my html screen. How can I load my data.json file? I don't want to use jquery. thanks

index.html

<html>
<head>

<head>
<body>
<script>

    var obj = JSON.parse(a);

    for (i in obj.types) {
       x+= "<h2>"+obj.types[i].name+"</h2>";
       x+= obj.types[i].age + "<br>";
    }
    document.getElementById("demo").innerHTML = x; 

</script>
</body>

output should be like this:

a1

30

a2

20

my json file

data.json

{
    "a": [
        {
            "name": "a1",
            "age": 30,
            "models": [
                "a",
                "b",
                "c"
            ]
        },
        {
            "name": "a2",
             age": 20,
            "models": [
                "a",
                "b"
            ]
        }   
],
    "b": [
        {
            "Number": "001",
            "Name": "b1",

        }
]
}

Upvotes: 0

Views: 82

Answers (2)

Atul Sharma
Atul Sharma

Reputation: 10740

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "./data.json", true);    
    xhr.onload = function (){
        obj = JSON.parse(this.responseText);
        var x = "";
        obj.a.forEach(function(e){
            x += "<h2>"+e.name+"</h2>";
            x += "<span>"+e.age+"</span>";
        })
  document.getElementById("demo").innerHTML = x; 
}
xhr.send();

make a ajax request to ./data.json your json file and parse it.

OR

Just add data to code itself.

var obj = {
    "a": [
        {
            "name": "a1",
            "age": 30,
            "models": [
                "a",
                "b",
                "c"
            ]
        },
        {
            "name": "a2",
             "age": 20,
            "models": [
                "a",
                "b"
            ]
        }   
],
    "b": [
        {
            "Number": "001",
            "Name": "b1",

        }
]
};

var x = "";
obj.a.forEach(function(e){
 x += "<h2>"+e.name+"</h2>";
 x += "<span>"+e.age+"</span>";

})

    document.getElementById("demo").innerHTML = x; 
<div id="demo">

</div>

Upvotes: 1

Minh Dao
Minh Dao

Reputation: 1

You can't load a file from local to browser. You need create serve for file json (example: http://localhost:8080/data.json) then you request to it

Upvotes: 0

Related Questions