How To Read & Write JSON

How To Read & Write JSON

JSON stands for JavaScript Object Notation; it’s based on JavaScript objects and other language types to create a structured file type for storing data. Now, after being in the community for a while, something has come to my attention. I’ve realized a lot of plugins ask the user to create or use a JSON file in RPGMakerMV. But, no one touches on JSON itself; this tutorial is here to demystify JSON. We’re going to cover syntax, common rules, and legal types in JSON files.

 

JSON Syntax

Before you can write, you have to be able to read. JSON syntax has three major components: objects, lists, and properties.

Objects are enclosed in curly brackets. Here’s an example:
{ "Property1": 2 }

Now, the next component is the list.

Lists are enclosed in square brackets; the list could contain objects, strings, numbers, booleans, and even other lists. Remember these, they are crucial to understanding JSON and reading it. Now, here’s an example of a list:
["Candy", "Popsicles", "Chicken", "Teriyaki"]
As you can see the list has different values separated by commas to signal different values; this is similar to arrays in JavaScript.

Now, the last major component is properties.

Properties are enclosed in double quotes. They are the names of keys that hold a certain value; some of these possible values were mentioned above. Here’s an example of a property:
{"Property1": ["Candy", "Food", "Chicken"] }
As you can see in this example the property or key, is called “Property1”, and has a list as it’s value. This and the above code snippets are good examples of proper JSON. Now, this covers all the syntax allowed in a JSON file. Now, let’s go through common rules.

 

Common Rules

  1. Don’t put any comments in your JSON file; the JSON file won’t be able to be interpreted.
  2. Place a comma after every new valueexcept the last one; this is the proper way to write JSON.
  3. Start your JSON file as an object or list; any other style won’t be interpreted properly.
  4. Numbers can’t be keys/properties.
  5. Don’t use illegal types.

 

Speaking of types, let’s go over the legal types in a JSON file.

 

Legal Types

There are five legal value types for a JSON value; these values types are object, list, string, number, and boolean. Here’s an example of each one and a sample JSON file showcasing all we’ve learned:
String: "Hello World"
Number: 2
Boolean: true, false
Object: {"key1": "My Best Day"}
List: ["JavaScript", "Python", "C++", "C#", "Java"]

Here’s the JSON file sample:

In this case, we have a JSON file starting as an object. As a result, every value needs to have a key/property to define it. This is often the best way to create your JSON files. Lists are good if you have a predefined structure of records or objects, you want to keep track of.

 

And that’s all the magic behind JSON files; enjoy all the new knowledge!

Leave a Reply

Your email address will not be published.