tutorial-json

English / Spanish

About

tutorial-json is a tutorial about how to write and read JSON files, in order to write your own databases and access other databases.

This tutorial was written by Aarón Montoya-Moraga. If you want to check out more tutorials, visit http://montoyamoraga.io/education.

It is also available in Spanish. It is written in Markdown and hosted in GitHub.

Introduction

JSON is a syntax for storing data.

It can be easily parsed by JavaScript, and it is heavily used in databases for this same reason.

The syntax of a JSON object can be summarized as follows:

Writing your own JSON file

example0.json

This is the simplest JSON object. It has one key/value between curly braces {}.

{
  "key": "value"
}

example1.json

Let’s add more key/value pairs to this JSON object, making sure to add commas, and not using one after the last pair.

{
  "key": "value",
  "otherKey": "otherValue",
  "lastKey": "lastValue"
}

example2.json

Let’s add now other types of values to the JSON object.

{
  "key": "value",
  "otherKey": "otherValue",
  "aNumber": 38.0,
  "aBoolean": false,
  "null": null,
  "lastKey": "lastValue"
}

example3.json

Now let’s take this first JSON object inside of curly braces{}, and put it inside of an array, using square brackets []. After this first an array of JSON objects, write a second pair of curly brackets {} to create a second JSON object on the array, separating them with commas. Remember that the last key/value pair inside of each JSON object should not followed by a comma.

[
  {
    "key": "value",
    "otherKey": "otherValue",
    "aNumber": 38.0,
    "aBoolean": false,
    "null": null,
    "lastKey": "lastValue"
  },
  {
    "testing": "value",
    "other-test": "otherValue"
  }
]

example4.json

Now let’s use a JSON object as a value

[
  {
    "key": "value",
    "otherKey": "otherValue",
    "aNumber": 38.0,
    "aBoolean": false,
    "null": null,
    "lastKey": "lastValue"
  },
  {
    "testing": "value",
    "other-test": "otherValue",
    "jsonObjectAsValue": {
      "year": 2018,
      "month": "March"
    }
  }
]

Typical mistakes

JSON and JavaScript

//this returns a JavaScript object
JSON.parse()

JSON in projects

Contents of this repository:

This repository contains examples in:

References

Thanks