Episode 7: JSON

In the last couple episodes I talked about how I separated my code into different components. First I broke it down into states, then into factories. I was feeling really good about how I was organizing things, and I had an idea about how I could make it even better: JSON.

What Is It?

If you don’t know what JSON is, it’s basically a way of storing data in a format that JavaScript can understand. JSON stands for JavaScript Object Notation, and that’s exactly what it is: the code for a JavaScript object. As an example, let’s say we wanted to create an object in our JavaScript file. There’s two ways we can do it:

First, we can use a constructor…

And then create an instance of the object…

The second way we can do this is by describing the object literally…

This is how JSON works. You just describe a literal JavaScript object and save it in a file. Then you just load the JSON file into memory. No parsing, no reading lines, no need to define delimiters and special characters. A number of libraries even simplify the process of loading the file, including Phaser…

The reason this takes two steps is that the JSON file is loaded asynchronously, which just means that the computer keeps doing other stuff instead of waiting for the file to load.

Magic Numbers

So how could JSON help make my code better? Well any time I encounter a magic number, I can move it to a JSON file. If you don’t know what magic numbers are, they’re these nasty critters that make your code confusing and difficult to maintain…

In the code above, our x and y values for the sprite’s location are magic numbers. They’re magic because they aren’t based on any logic or conditions. They’re just hard-wired into the code.

It would be better to set the x and y values based on the game’s resolution…

This works fine, but it would probably be even more smarter to move the starting location to a JSON file called something like settings.json and store it in an appropriately-named object…

Once we’ve loaded the JSON file into a variable (like GameSystem.settings), we can then create the player’s sprite without using any magic numbers…

As I kept exporting more and more magic numbers out of my code, I found that my settings.json file was pretty big and difficult to read, so I decided to create a number of JSON files and store relevant stuff in each of them. Here’s what I ended up with:

  • settings.json
  • assets.json
  • items.json
  • entities.json
  • factions.json
  • menu.json
  • worlds.json
  • missions.json

I know I said this in the last episode, but I’ll talk more about these things in the future.

Anyway, JSON is awesome. I don’t know what a professional game programmer would think of this approach, but it works for me!

Leave a Reply