I have stored json data in “.json” extension file as given format. I want to add json data inline for minimizing load on server dude to large data.
Students.json :
[
{"id": 1, "name": "abc", "standard": "5 th","dob": "2001-1-4"},
{"id": 2,"name": "pqr", "standard": "5 th","dob": "2001-2-4"}
]
By using jquery or JavaScript, I want to use this json data to be utilized in webpage. My first priority is to add json as inline data so it takes minimum amount to load page and less call to server.
It is the just example data to understand json format of file but it will be large amount of data, It will have around 20,000 records of student.
This is the great approach to add or embed inline json to html web page. Json can be added or embedded with three different ways:
1) Adding json data with in script tag in html web page.
In this we have to add all json data with in <script> tag. It will take minimum load on web page and reduce server ping.
<script type=”application/json” id=”jsonData>
[
{"id": 1, "data": "html", "style": "embeded","ajax": 1},
{"id": 2,"data": "html", "style": "inline","ajax": 2}
]
</script>
<script type=”text/javscript”>
//use of inline json data within script tag using jquery
$(document).ready(function(){
var data = JSON.parse($(“#jsonData”).htm());
});
//use of json inline using javascript
var data = document.getElementById(“#jsonData”).innerHTML();
</script>
2 : Get data of .json file using jquery’s.getJSON() :-
getJSON() is easiest way to get data from other remote url or file. It has some advantages but it has also some draw backs on that.
Advantage : File can be created easily by server and handled easily
Disadvantage :
- Large file will be truncated.
- Execution will be slower
Code:-
$.getJSON(“URL_PATH/file.json”,function(json_data){
var data = JSON.parse(json_data);
});
3)Another approach is by using $.ajax
It’s the simple usage using $.ajax.
$.ajax({
url:”URL/data.json”,
dataType:”json”,
success:function(res){
var data = JSON.parse(res);
}
});
4)json data with in .js file include with script tag
It’s the best approach among others to use json data with in the js file and include that file with script tag.
D3.js is using same method to get large data for the chart.It really loads faster data then other things.
Json_file.js
var flare_data=[ {“id”:1,”data”:”html”,”script”:”js”},
{“id”:2,”data”:”php”,”script”:”php”}
];
json data will be stored like above file and utilized like below code of javscript’s script tags.
<script type=”text/javascript” src=”Json_file.js”> </script>
<script type=”text/javascript”>
var data = JSON.parse(flare_data);
</script>