Skip to main content

JSON Import

JavaScript Object Notation (JSON) is a data interchange format based on JavaScript, the world's most popular programming language. It has especially become popular for web APIs and configuration files because it is structured and much more lightweight than its predecessor, XML.

Here is an example of a JSON file that could be imported into Easel:

{
"width": 28,
"height": 42,
"entities": [
{
"type": "cheese",
"image": "cheese.svg",
"x": 10,
"y": 20,
"qty": 5,
},
{
"type": "mouse",
"image": "mouse.svg",
"x": 30,
"y": 40,
},
],
}

Raw import​

The following example imports the data from level1.json into a variable called Level1Data:

pub import Level1Data from @level1.json

This will import data as-is, without any conversion. Notably, if you are importing a JSON file, all keys will be Strings, not Symbols, which means you have to use Level1Data["entities"] instead of Level1Data.entities to access a field.

Schema import​

JSON files can only consist of basic types like Strings and Numbers. To take advantage of the full gamut of Easel's types, you can use the as keyword to convert the imported data to a specific schema:

pub import Level1Data from @level1.json as {
width as Number,
height as Number,
entities as [{
type as Symbol,
image as Asset,
pos = @(x, y),
}],
}

Because this import has a schema, you can now access the data using Level1Data.entities[0].type.

info

See Schemas for more information on how to define schemas.

Parsing parameters​

You can parse the file using the Json function, but unlike Csv, there are no additional parameters available for Json files, so this is only included for completeness:

pub import Level1Data from Json(@level1.json)

JSON5 support​

Easel supports JSON5, which is a superset of JSON that aims to make it easier for humans to write and maintain. It allows for comments, trailing commas, and unquoted strings. This reduces unnecessary friction of writing JSON files. See json5.org for more information on the JSON5 format.