How to get JSON array from file using getJSON?

How can I get json array of json file with javascript and jquery

I was a trigger with the following code since it does not work:

var questions = []; function getArray(){ $.getJSON('questions.json', function (json) { for (var key in json) { if (json.hasOwnProperty(key)) { var item = json[key]; questions.push({ Category: item.Category }); } } return questions; }) } 

this is a json file named: questions.json

 { "Biology":{ "Category":{ "cell":{ "question1":{ "que1":"What is the cell?" }, "option1":{ "op1":"The cell is the basic structural and functional unit", "op2":"is a fictional supervillain in Dragon Ball" }, "answer1":"opt1" } } }, "Astronomy":{ "Category":{ "Mars":{ "question1":{ "que1":"How many moons does Mars?" }, "option1":{ "op1":"5", "op2":"2" }, "answer1":"opt2" } } } } 

I want to get an array with this format {Biology: {Category: {cell: {question1 ....}}}}

+6
source share
2 answers

$.getJSON is an asynchronous function, so returning something inside this function does nothing, because it is not in scope or not received. You should probably do something like:

 function getArray(){ return $.getJSON('questions.json'); } getArray().done(function(json) { // now you can use json var questions = []; $.each(json, function(key, val) { questions[key] = { Category: val.Category }; }); }); 
+9
source

Your condition in the for loop does not allow you to add anything to your array. Instead, check to see if your json object has a property, then get the value and add it to your array. In other words:

if (questions.hasOwnProperty(key)) should be if (json.hasOwnProperty(key))

In addition, you cannot simply return to get the result of such an AJAX call, because the method runs asynchronously. This return actually applies to the internal callback to the success function, not getArray . You must use the callback template to transfer data only after receiving it and act accordingly.

(Of course, since the array is defined in the outer scope, you would not need to return it anyway, but if you try to use it before the AJAX method ends, it will be empty.)

Assuming you are going to display it in the DOM using a method called renderJSON :

 var questions = []; function getArray(){ $.getJSON('questions.json', function (json) { for (var key in json) { if (json.hasOwnProperty(key)) { var item = json[key]; questions.push({ Category: item.Category }); } } renderJSON(questions); }); } 
+3
source

All Articles