2

I have a JSON array saved to its own file, gamedata.json. If this were instead just a regular array of objects like gamedata.js loaded into my HTML, I could just give the array a name var gameObjects = array [{lots of objects}]; and then if I wanted to look through the array I could just reference gameObjects, even from other JS files loaded into the same HTML page.

But since this is a JSON file, how can I reference it? This is my first time working with JSON but I learned that I can't set the array to a variable in the .json file. So how can I get access to it's data from other JS files?

I can use VanillaJS or jQuery, its a large array, around 13000 lines, so efficiency matters.

Chirpizard
  • 291
  • 3
  • 17
  • 5
    What is the context - Node.js or a browser or something else? You have to import the JSON as text, parse it with `JSON.parse()`, and assign the result of that to a JavaScript variable. Exactly how you do that depends on the relationship between the execution environment of the JavaScript code that needs access, and the location/situation of the JSON file. – Pointy Jan 02 '16 at 21:49
  • The above comment is correct. THere are two very different approaches to reading data from the filesystem. I think you are in the browser since you mentioned jquery. – t3dodson Jan 02 '16 at 21:53
  • Sorry, should have been more clear. Browser. How do you import it the JSON as text? – Chirpizard Jan 02 '16 at 22:05

2 Answers2

1

Possible solution could be:

var myJson;
$.getJSON("z.json", function(data) {
  myJson = data;
});
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • This solution works. Pretty simple. It happens asynchronously, right? So when I'm trying to reference ```myJson``` it says undefined. So I just put the code that will reference ```myJson``` inside of the ```getJSON``` function. Is this alright to do? It seems to work. – Chirpizard Jan 02 '16 at 22:31
  • @Chirpizard Yes, it's asynchronous. Could you accept and upvote? – gaetanoM Jan 02 '16 at 22:32
0

Using fetch, which is supported in some modern browsers, but can be polyfilled

fetch( 'gamedata.json' )
  .then( res => res.json() ) 
  .then( data => {
    // data is available here and has been parsed into an array already
  })
  .catch( err => errorHandler )

If you use browserify then it'll pull the json file into your javascript bundle and expose that as a module (not sure if other bundlers such as webpack or jspm have the same mechanism) i.e.

var data = require( 'gamedata.json' )

But note that it does this at build time, if your json file is dynamic then this implementation wont work for you.

Matt Styles
  • 2,442
  • 1
  • 18
  • 23