0

I contents of this site to the file at App/data/names.js directory in my solution: https://raw.githubusercontent.com/dominictarr/random-name/master/names.json

I did it because the array is too big to put in my file where I write my code and initialize a variable with it explicitly. But still, I would like to assign it to the variable I created. I have mind something like this.

var arrayOfNames = readJSonFromFile("path");

Is it possible to achieve?

halfer
  • 19,824
  • 17
  • 99
  • 186
Yoda
  • 17,363
  • 67
  • 204
  • 344
  • Possible duplicate of [Loading local JSON file](http://stackoverflow.com/questions/7346563/loading-local-json-file) – Rajesh Oct 18 '16 at 10:06

2 Answers2

1

Like this!

$.getJSON('path', function (arrayOfNames) {
// do things with your arrayOfNames
} );
Anna Jeanine
  • 3,975
  • 10
  • 40
  • 74
0

You can fetch the document with an HTTP request from JavaScript, sort of like this:

function do_something(arrayOfNames) {
  console.log(arrayOfNames)
}

var xhr = new XMLHttpRequest();
xhr.open('get', 'https://raw.githubusercontent.com/dominictarr/random-name/master/names.json', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      do_something(JSON.parse(xhr.responseText))
    }
  }
}
xhr.send()

Note that this may not work on ancient browsers. Depending on whether you're using some JavaScript framework there is probably a shorter solution.