Shubhankar Chowdhury
Shubhankar Chowdhury

Reputation: 69

I am developing a website in which i want to read some json file locally in my js file

data = {"items": [
                   {
                        "title": "sample 1",
                        "author": "author 1"
                   },
                   {
                        "title": "sdample 2",
                        "author": "author 2"
                   }
]};

This is my json file.

Now I want to read this local json file in my js to print the values of json in HTML page I dont want to use any httpsRequest.

NOTE: I am not using any web server

Below is my JS file

function data(languageClass){
		var news = document.getElementsByClassName(languageClass)[0];
		  	var item = json.items;// where json is local json copy which i want
 console.log( "hiiii" +	item);
		for(var i = 0; i < item.length; i++) {
		    var h5 = document.createElement("h5");
		    
		    h5.innerHTML = item[i].title;
		 
		    news.appendChild(h5);
		    var p = document.createElement("p");
		    p.innerHTML = item[i].author;
		    news.appendChild(p);
	}
		
		
}

below is my HTML file :

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 <script type="text/javascript" src="D:/Shubhankar/web/quess.json"></script> 
<script type="text/javascript"
    src="../web/Question.js"></script>

<title>Java Interview Question</title>
<link rel="icon" type="image/png" href="../img/icon.png">
</head>
<body onload='data("interviewQuestions")'>

    <div class="interviewQuestions"></div>
</body>
</html>

Upvotes: 0

Views: 75

Answers (1)

Aniket Sinha
Aniket Sinha

Reputation: 6031

data = {"items": [
                         {
                           "title": "sample 1",
                           "author": "author 1"
                         },
                         {
                          "title": "sdample 2",
                          "author": "author 2"
                         }
]};

This is not a valid JSON.

Without web server or XHR request, you cannot load your data. One way to get this data in your app is to have a JS file with JSON content in it. Sample:

var data={"items": [
    {
      "title": "sample 1",
      "author": "author 1"
    },
    {
      "title": "sdample 2",
      "author": "author 2"
    }
  ]
}

Now call this JS file using script tag.

<script src="path/to/jsonfile.js"></script>

Upvotes: 3

Related Questions