I have a JSON file data.json
with the following content:
[
{
"name": "Alice",
"number": 10
},
{
"name": "Bob",
"number": 20
},
{
"name": "Mary",
"number": 50
}
]
And I want to read this JSON file and extract the value of key: number
into an array:
number_array = [10, 20, 50]
Here is my way:
First I read the JSON file into a string
function readTextFile(file) {
var raw_text;
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
raw_text = rawFile.responseText;
}
}
rawFile.send(null);
return raw_text;
}
However, when I call this function,
var result = readTextFile('data.json')
I cannot get the correct result but an undefined
.
I am asking how can I read the JSON file and store it into a global variable (not only within the function local variable). Thank you.