DEV Community

Cover image for A Straightforward Guide to Building and Using a JSON Database File
Pri
Pri

Posted on

A Straightforward Guide to Building and Using a JSON Database File

What is a db.json file?

A db.json file is a JavaScript Object Notation (JSON) file that is used to store and transport organized data in a format that is easy to read; often when data is sent from a server to a web page.

JSON is language independent, meaning the JSON syntax is developed from JavaScript object notation syntax, but the JSON format is only in text format. The code used for reading and creating JSON data can be written in other programming languages.

Why is a db.json file ideal?

A db.json file is lightweight, easy to read, and does not require a complex setup, which makes it easy for developers to understand and modify data. db.json files are ideal for local development or prototyping frontend applications. During development, data often needs to be stored somewhere temporarily without needing to set up a full database; a db.json file provides that simple solution.

Certain tools, such as a JSON Server can transform a db.json file into a completely functional mock REST API. A mock REST API server "imitates a real API server by providing realistic responses to requests" (API Mocking Guide and Online Mock API Server Testing). This allows frontend developers to test API calls without a backend and mock-up a model of an application with realistic API responses.

For example, a db.json file like this:

{
  "topFiveUniversities": [
    {"id": 1, "name": "University of Oxford"},
    {"id": 2, "name": "Massachusetts Institute of Technology"},
    {"id": 3, "name": "Harvard University"},
    {"id": 4, "name": "Princeton University"},
    {"id": 5, "name": "University of Cambridge"}
 ]
}
Enter fullscreen mode Exit fullscreen mode

Can get a result in API endpoints like:
GET /topFiveUniversities: Retrieves the full list of universities
POST /topFiveUniversities: Adds a new university
PUT /topFiveUniversities/1: Updates the university with id:1
DELETE /topFiveUniversities/1: Deletes the university with id:1

What is the structure of a db.json file?

The following syntax defines dog breeds object, which are an array of three dog breed records (objects):

{
"dogBreeds":[
  {"breed": "Bernese Mountain Dog", "origin":"Switzerland"},
  {"breed": "Dogo Argentino", "origin":"Argentina"},
  {"breed": "Chihuahua", "origin":"Mexico"}
]
}
Enter fullscreen mode Exit fullscreen mode

The top-level key is "dogBreeds" (an array). The array items are each item in the array, which are objects with two key-value pairs "breed" and "origin."

Be sure to use camelCase or snake_case and avoid spaces in keys (e.g., "dog breeds"), as it can cause difficulties when constructing URLs and potential issues when accessing the keys in your code.

Rules of JSON Syntax

  • The data is organized as name/value pairs
  • The commas separate elements in arrays or key-value pairs in objects (except the last one)
  • The curly braces hold the objects
  • The square brackets hold the arrays

Rules of JSON Syntax Image

Breakdown of JSON Data

Name and Value

Name or value pairs are used in JSON data writing, much like the properties of JavaScript. A name or value pair has a field name in double quotation marks (" "), followed by a colon (:), followed by a value in double quotes (" "):

"breed":"Bernese Mountain Dog"
Enter fullscreen mode Exit fullscreen mode

JSON names must have double quotes; JavaScript does not.

Objects

The objects in a JSON file are written in curly braces. They can contain more than one name or value pairs, like in JavaScript:

{"breed":"Bernese Mountain Dog", "origin":"Switzerland"}
Enter fullscreen mode Exit fullscreen mode

Each name/value pairs should be separated by a comma and space.

Arrays

The arrays in a JSON file are written in square brackets. An array can contain objects, like in JavaScript:

"dogBreeds":[
  {"breed": "Bernese Mountain Dog", "origin":"Switzerland"},
  {"breed": "Dogo Argentino", "origin":"Argentina"},
  {"breed": "Chihuahua", "origin":"Mexico"}
]
Enter fullscreen mode Exit fullscreen mode

As seen above, the object "dogBreeds" is an array which contains three objects. Each object is stored information of a specific breed and its origin.

Some things to Keep in mind when building a `db.json file

  • If you open a curly brace {} or square bracket [], make sure to close them.
  • Include commas between array or objects
  • Use double quotes (" ") for strings
  • Do not include comments (JSON does not allow them)

Transforming JSON Text into a JavaScript Object

It is useful to convert a JSON text to a JavaScript object in cases where you may need to work with structured data in a more interactive manner. JSON is commonly used to read data from a web server and display it on a web page. You can use a string as input to structure it in a simple way. You can do this by creating a JavaScript string that contains JSON syntax:

Transforming JSON Text 1

You can use the JavaScript built-in function JSON.parse() to change the string into a JavaScript object:

Transforming JSON Text 2

Lastly, in your page, use the new JavaScript object:

Transforming JSON Text 3

Using a db.json file with a project

Node.js and npm will need to be installed on your computer. Continue onto the following steps to set up and use JSON Server in your application:

1. Install the JSON Server

  • In your terminal or command prompt, navigate to your project directory and type:

npm install -g json-server

  • This will globally install the JSON Server in your computer.

2. Create a JSON File

  • In your project directory, create a JSON file using VSCode or a code editor of your choice. Your JSON file should have a .json file extension, such as db.json. This is where you will write your JSON data.

3. Construct Your Data

  • Establish your data inside the db.json file as an array of objects or an object with nested objects. Each object should have a unique id, as it represents a data entity.

4. Start the JSON Server

  • Start your JSON Server by typing the following into your terminal:

json-server --watch db.json

  • This will run by default on http://localhost:3000. Access the API at http://localhost:3000.

References

“API Mocking Guide and Online Mock API Server Testing.” Stoplight - A Smartbear Company, https://stoplight.io/mock-api-guide#:~:text=A%20mock%20API%20server%20imitates,types%2C%20objects%2C%20and%20arrays. Accessed Dec. 2024.

“JavaScript JSON.” W3Schools Online Web Tutorials, www.w3schools.com/js/js_json.asp. Accessed Dec. 2024.

Ofoegbu, Juliet. “How to Use JSON Server for Front-End Development.” freeCodeCamp.Org, freeCodeCamp.org, 21 Aug. 2023, www.freecodecamp.org/news/json-server-for-frontend-development/.

What Is JSON | Explained, Hostinger Academy, 24 Nov. 2022, https://youtu.be/cj3h3Fb10QY?feature=shared. Accessed July 2024.

“World University Rankings.” Times Higher Education (THE), 16 Dec. 2024, www.timeshighereducation.com/world-university-rankings/latest/world-ranking.

Top comments (0)