15.1. Introduction to JSON

JSON (i.e., JavaScript Object Notation) is a common text format for describing the state of objects. As it name suggests, its syntax is based on the JavaScript programming language; however, one need not know JavaScript to use or work with JSON. The JSON format is used in a variety contexts, including web application development, and software libraries and tools exist to help programmers work with JSON both inside and outside of the software they develop.

15.1.1. Starter Code

Use the following command to download the starter code and place it into a subdirectory called cs1302-json:

sh -c "$(curl -fsSl https://cs1302uga.github.io/cs1302-book/_bundle/cs1302-json.sh)"

After downloading the starter code, change into the cs1302-json directory so that you can follow along and interact with the same files mentioned in the examples!

15.1.2. Basic Syntax

<<<<<<< HEAD In a JSON, text is arranged in specific way to describe the contents of an object. Here are the basic rules: ======= In JSON, text is arranged in specific way to describe the contents of an object. Here are the basic rules: >>>>>>> main

  • : is used to pair a key / variable name with a value;

  • "" is used to denote a key / variable name or a string literal value;

  • nn is used to denote a numeric literal (e.g., nn can be 2 or 3.5);

  • {} is used to denote an object; and

  • [] is used to denote an array.

15.1.3. Creating JSON Text

If the jo command is available, like it is on Odin, then you can use the jo command to create JSON text using command-line arguments. For example, to see what an object with an id variable that stores the int value 42, you can execute the following command:

jo id=42
{"id":42}

The output above likely looks a little crowded. To tell jo to pretty-print its output, use its -p option:

jo -p id=42
{
    "id": 42
}

Let’s adjust the command so that our object also contains a String referred to by the key or variable named name:

jo -p id=42 name="bob"
{
    "id": 42,
    "name": "bob"
}

To learn more about the jo command, refer to its manual page using man jo.