Fendo
Fendo

Reputation: 21

retrieve single object from json file

Is it possible to just retrieve a single object of an .json file? What i have is:

data.json

{
  "0": {
    "test": "0"
  },
  "1": {
    "test": "1"
  }
}

script.js

  var data = "";
  var Id = '1';

  $.getJSON(linktofile, function(data) {
    data = data;
    if (data[Id] == null) {
      x = "<h4>Any Text</h4>";
      document.getElementById("demo").innerHTML = x;
    } else {
      if (data[ID].test != 0) {
        x += "<span>" + data[ID].test + "</span>";
      }
    document.getElementById("demo").innerHTML = x;
    }
  });

At the moment I get the complete data from the .json file. My problem is that the .json file is over 5000 lines long and sometimes it took 1 second or 2 to finish the complete function. Is there any thing like:

script.js

$.getJSON(linktofile, function(data[Id]) {
  //do anything with the data
});

So I only retrieve the part I need and not the complete data?

Upvotes: 2

Views: 1422

Answers (1)

awran5
awran5

Reputation: 4546

JSON demo data file from JSONPlaceholder

(function() {

$.getJSON( "https://jsonplaceholder.typicode.com/users", function( json ) {
		
	// Specify the index to retrieve
	var index = 1;
		
	// Get specific index data
	var data = json[index];

	// Get the name for example
	document.getElementById("demo").innerHTML = data.name;

});

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="demo"></div>

Upvotes: 1

Related Questions