-1

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.

VICTOR
  • 1,894
  • 5
  • 25
  • 54
  • Because your request is async (third parameter for [`open`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open) is set to `true`), did you mean to use a sync request? – Patrick Evans Sep 08 '16 at 14:53
  • 1
    @PatrickEvans - don't encourage synchronous requests - they're deprecated as it is – Jaromanda X Sep 08 '16 at 14:54
  • @JaromandaX, wasn't encouraging it, was asking if that is what they meant to do. As they might be purposely wanting a sync request fully aware of the cons against it. – Patrick Evans Sep 08 '16 at 14:55
  • @PatrickEvans - just as well :p – Jaromanda X Sep 08 '16 at 14:55
  • Sorry. I am new to Javascript. It seems like I should looking for the return value from an async function? – VICTOR Sep 08 '16 at 15:03
  • @Jaromanda X After looking up the answer, I still cannot find the way to return the value from async function.... – VICTOR Sep 08 '16 at 15:26

1 Answers1

1

Despite having marked this question as a "duplicate", I believe a few points are worth mentioning to the OP:

First, if you are using D3, there is no need of using XMLHttpRequest to get the JSON. D3 has a function just for that:

d3.json("filename.json", function(data){
    //code using `data`
});

Second, and the most important: why do you want to store the JSON in a global variable? There is absolutely no reason to do that. Once d3.json loaded your json, you can do everything inside the callback.

For instance, inside the callback, you can simply map your data array to get your desired outcome (once d3.json don't work in SO snippet, I'm using a variable here):

var data = [{"name": "Alice","number": 10},
   {"name": "Bob","number": 20},
   {"name": "Mary","number": 50}];

var newData = data.map(function(d){ return d.number});
console.log(newData);

Altogether, this is the code:

d3.json("filename.json", function(data){
    var newData = data.map(function(d){ return d.number});
});
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • Thanks for your reply. I want to store the json in a global var as I may have some manipulation on the data. I want to ask in line `var newData = data.map(function(d){ return d.number});`, I still cannot return `newData` to the main function variable, right? – VICTOR Sep 08 '16 at 15:54
  • You can do any data manipulation you want inside `d3.json`, and you can create how many callbacks you want... – Gerardo Furtado Sep 08 '16 at 15:55
  • I am very new to both d3 and js. Is it very common to have many callbacks in a function in js? And I dont understand what do you mean by `do any data manipulation you want inside d3.json` – VICTOR Sep 08 '16 at 15:58
  • 1
    `d3.json` will load your JSON and create an array (in your case) named `data`, or whatever other name you give it. You can manipulate this array any way you want. That's it. I advise you to study some examples, there are several good examples of code available, specially in bl.ocks.org – Gerardo Furtado Sep 08 '16 at 16:01
  • Oh, Do you mean I should do all data manipulation within `d3.json( )` <---function – VICTOR Sep 08 '16 at 16:01
  • Yes, that's what I meant. – Gerardo Furtado Sep 08 '16 at 16:01