15.1. Introduction to JSON¶
JSON (i.e., JavaScript Object Notation) is a common plain 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 many 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¶
In JSON, plain text is arranged in a specific way to describe the contents of an object. Here are the basic rules:
:
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 be2
or3.5
);{}
is used to denote an object; and[]
is used to denote an array.
If data are said to be formatted using JSON, then that means the data
describes one or more objects and is stored or displayed in plain text
according to these rules. Here is a quick example of what the data for
an object with two variables (i.e., id
and name
) might
look like when formatted using JSON:
{
"id": 42,
"name": "bob"
}
Pretty Printing
To help programmers better understand the structure of data formatted using JSON, it is common for JSON-related tools to to include white space, indentation, and newline characters outside of variable valuesobjects. Displaying JSON in this manner is often called pretty printing.
{"id":42,"name":"bob"}
Compact Printing
To save space and mitigate network lag, JSON is often stored and transmitted in a compact or minified form that omits white space, indentation, and newline characters outside of variable values. The JSON shown above represents the same data that was shown in the pretty printing example but presented in a more compact form:
15.1.3. Creating JSON Text¶
If the jo command is available, like it is on Odin, then
you can use jo 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 the -p
option:
jo -p id=42
{
"id": 42
}
The next example adjusts the command so that the object we want to
describe using JSON also contains a String
value 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.