© Wallace Jackson 2016

Wallace Jackson, JSON Quick Syntax Reference, 10.1007/978-1-4842-1863-1_5

5. JSON Arrays: Serialized Data Store Structures

Wallace Jackson

(1)Lompoc, California, USA

This chapter examines a data structure that holds more complex data representations: an array. An array is similar to a database structure, but far more simplified in nature. Arrays are found in most every programming language, including OOP languages as well as non-OOP languages. You even hear the word array used in natural languages, such as in the phrase “We have a wide array of products,” referring to a store’s stock or collection of items to be sold.

In this chapter, you look at what an array of data is and how it is used and accessed using JavaScript, because this language is tied the most closely to JSON. After that, you see how arrays of data are represented using JSON, and how the popular Java open source language supports JSON arrays using custom classes and libraries.

An Overview of Arrays: Data Structures

The term array is most often used to mean the array data type. This is a type of data collection that is provided by almost all high-level programming languages. An array consists of an ordered collection of data values held in variables that can be selected by your code constructs. This is done by using one or more indices that are computed at runtime. In some cases, the term vector is used in computing to refer to an array, although tuple is the more correct mathematical equivalent and is another synonym. Arrays are often used to implement data tables, especially lookup tables in databases. For this reason, the word table is also sometimes used as a synonym for array.

An array is the oldest and most important computer programming data structure: holds the data to be operated on and is used by almost every software program ever coded. Arrays are also used to implement other important data structures, such as strings and lists. This is because arrays effectively use the inherently linear memory addressing logic and schema used by modern-day computers.

In most computers, as well as most external storage devices, the memory is a one-dimensional array of byte words, whose indices are the memory addresses themselves. Processors, also known as CPUs, are also optimized for array operation so that data can be quickly and efficiently retrieved, speeding up application performance and therefore also enhancing the user experience.

Array data types are implemented using some type of array structure . These may vary across languages and are often implemented by using hash tables, linked lists, search trees, and similar data structures that are all akin to simplified databases (data stores). In computer programming, an array data structure, usually referred to simply as an array, is a data structure consisting of a collection of elements (data values held in variables).

Each of these elements is identified by at least one array’s index. An index is also sometimes referred to as the key because it allows you to reference (retrieve) the data. The simplest type of data structure is a linear array, also called a one-dimensional array.

An array is stored in such a way that the data access (position in the array) for each element can be computed from the array index or key using a basic mathematical formula to access linear data items (records). As an example, the array of eight 32-bit integer variables with indices 0 through 7 is stored as eight words at memory addresses 2000, 2004, 2008, 2012, 2016, 2020, 2024, and 2028. So, the element with index i has the address index[i] = 2000 + 4 × i.

There are also two-dimensional arrays , sometimes referred to as matrices because the mathematical concept of a matrix can be represented as a two-dimensional grid; there are three-dimensional arrays as well. The data elements of array data structures are usually required to have the same data size and the same data structure, and also use the same data-type representation, so that an element index can be accurately computed during runtime. Among other things, this data-uniformity requirement allows any single iterative statement to process an arbitrary number of data elements in any data array. Sets of valid index tuples and the addresses of the elements, and hence the element-addressing formula, usually, but not always, are 100% fixed while a data array is being accessed.

Declaring a JavaScript Array: Variable Declaration

Let’s follow the format used in Chapter 4 and first look at how to define a data array using the JavaScript programming language. Then you see how to access this data using JavaScript dot notation (this works in Java as well) and how arrays can be represented using JSON. Similar to soft-object literal notation, you start the array data declaration with the var (variable) keyword and the name that you wish to use for your array, followed by an equals operator. Instead of the curly braces {...} used for defining objects, arrays use square brackets [...] instead. To define an array containing a used car dealership’s inventory, including make, model, color, and list price, you can create an array data structure where each data record is an object, with colon-delimited key:value pairs separated using commas, and with the object definitions themselves separated by commas within the array, which is defined using square brackets. Remember that attribute names and string values are contained in double quotes. The JavaScript code looks like the following array data definition:

var carInventory = [
    { "carName":"Toyota", "model":"Prius", "color":"Green", "price":24995 },
    { "carName":"Nissan", "model":"300ZX", "color":"Brown", "price":21795 },
    { "carName":"Dodge",  "model":"Viper", "color":"White", "price":26495 },
    { "carName":"Chevy",  "model":"Camaro", "color":"Blue", "price":27895 }
]

Now that you have defined an array of data objects, let’s look at how you access elements of arrays using the array name, element indices, object properties, and dot notation.

Accessing a JavaScript Array: Using the Index

Array data elements are accessed by using their indices, which are contained in square brackets just like the array itself. As you may imagine, the array name comes first, using an integer index specification, to specify which data record you wish to access. Then the dot-notation syntax is used to chain together that data record with the property name you wish to reference. The following example puts together a construct that accesses the first (carName) object attribute ("Toyota"):

carInventory[0].carName       // Will return the String value: "Toyota"

You can also concatenate data together using a plus operator and insert blank space using quotation mark delimiters with a space in between. The following example takes a carName object attribute and appends it to the model object attribute, creating the full car manufacturer and model name as a result ("Toyota Prius"):

carInventory[0].carName + " " + carInventory[0].model     // "Toyota Prius"

There’s an alternate way to access object attributes in an array data record, which does not use dot notation. This involves using the square brackets used with arrays to hold a quoted attribute name value. So instead of using arrayName[n].attributeName, you can use [n]["attributeName"], as shown in the following JavaScript code example:

carInventory[0]["carName"]   // Will also return the String value: "Toyota"

Again, you can concatenate data together using a plus operator and insert blank space using quotation mark delimiters with a space between them. This example takes a carName object attribute and appends it to the model object attribute, resulting in the manufacturer and model name ("Toyota Prius"):

carInventory[0]["carName"] +" "+ carInventory[0]["model"] // "Toyota Prius"

You can create constructs that access the array object data in whatever order suits your purpose. The following data-access example outputs a more descriptive formatting of the object data, perhaps for sales and marketing purposes:

carInventory[3].color   + " "   +
carInventory[3].carName + " "   +
carInventory[3].model   + ": $" +
carInventory[3].price             // Returns: "Blue Chevy Camaro: $27895"

This can also be represented using the alternate array object attribute data -access format, which uses the following JavaScript code syntax:

carInventory[3]["color"]   + " "   +
carInventory[3]["carName"] + " "   +
carInventory[3]["model"]   + ": $" +
carInventory[3]["price"]            // Returns: "Blue Chevy Camaro: $27895"

Next, let’s look at the syntax for defining an array using JSON. This is similar to the JavaScript approach but uses a colon instead of the equals operator and does not use the var (variable) keyword. After that, you look at how Java 8 provides JSON array and object libraries for handling the object and array structures you saw in the previous two chapters.

Defining a JSON Array: Using the Colon Operator

The basic format for JSON array data structures can be found on the json.org web site and uses square brackets to contain the data values, which are comma delimited (separated by commas). You saw this in the previous section, where you separated data objects using commas, with each object structure contained in curly braces. The basic JSON array format diagram, from json.org, is reproduced in Figure 5-1.

A417940_1_En_5_Fig1_HTML.jpg
Figure 5-1. A JSON array is contained in square brackets and uses commas to separate values

A basic JSON array of number values thus uses the following data format:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]

The name for a JSON array is contained in double quotation marks, using the colon operator between the JSON array name and the JSON array structure itself. Here is an example of how the array data structure from the previous section is created as a JSON array data definition structure:

"carInventory" : [
    { "carName":"Toyota", "model":"Prius", "color":"Green", "price":24995 },
    { "carName":"Nissan", "model":"300ZX", "color":"Brown", "price":21795 },
    { "carName":"Dodge",  "model":"Viper", "color":"White", "price":26495 },
    { "carName":"Chevy",  "model":"Camaro", "color":"Blue", "price":27895 }
]

Now that you’ve seen the two major JSON data structure types, objects and arrays, the next section presents an overview of the Java 8 programming language capabilities regarding JSON, and after that, you can proceed to the chapters covering numbers, characters and other data values.

Java JSON Support: JSON Utility Classes

Java has an API called JSR 353 created solely for JSON data processing. This API provides portable API components that allow you to parse, generate, transform, and query JSON data definitions using both Object Model and Streaming API libraries and classes. The JSON Object Model API creates a random-access, tree-like structure that represents the JSON data in system memory. This tree-like data structure can subsequently be navigated or queried.

The object programming model is the most flexible approach, enabling processing that requires a random access to the complete contents of the object data-tree structure. This object model usually is not as efficient as a streaming model, requiring more system memory to implement, because it must install the entire data representation into system memory locations.

The JSON Streaming API provides a way to parse and generate JSON using a streaming approach without having to have all the data in memory at one time. This streaming model gives you JSON parsing or generation control. The JSON Streaming API provides an event-based parser, letting you request the next event rather than handle the event using an event callback infrastructure.

This approach gives you more procedural control over JSON data processing. JSON streaming model application code can process or discard the parser event and ask for the next event, which is called pulling the event.

The streaming model is appropriate for local processing, where random access of other parts of JSON data is not required. Additionally, the JSON Streaming API provides a way to generate well-formed JSON to a stream by writing one event at a time.

JSON Object Model: Java Object and Array Builder

The JSON Object Model API is similar to the Document Object Model (DOM) API for XML or HTML5. The JSON Object Model is a high-level API that provides immutable object models for JSON object structures, which you learned about in Chapter 5; and JSON array structures, which you saw earlier in this chapter. These JSON structures are represented as Java object models using the Java types JSONObject and JSONArray.

The JSONObject class provides a Map object view to access an unordered collection of zero or more key:value pairs from a JSON data-object definition model. The JSONArray class provides a List object view to access an ordered sequence of zero or more values from a JSON data-array definition model.

The JSONObject, JSONArray, JSONString, and JSONNumber classes are subclasses, and therefore subtypes, of the JSONValue superclass. Constants are defined in this JSON API for null, true, and false JSON values, which are covered in Chapter 6. These are held in the JSONNull and JSONBoolean subclasses.

The JSON Object Model API uses builder patterns to create JSON object models from scratch. Application code can use the JSONObjectBuilder interface to create the JSON data-definition models that represent JSON objects. The resulting model is of the Object type JSONObject.

Application code can use the Java interface JSONArrayBuilder to create models that represent JSON Array Objects. The resulting model from this type of builder is of Object type JSONArray.

These object models can also be created using an input source (such as InputStream or Reader) using the Java interface JSONReader. Similarly, these object models can be written to an output source, such as OutputStream or Writer, using the Java class JSONWriter. These classes and interfaces are shown in Table 5-1, which lists the primary Java classes and Java interfaces contained in the JSON Object Model API for the Java programming language.

Table 5-1. Primary Classes and Interfaces in the Java JSON Object Model API

Class or Interface

Description

JSON

Contains static methods to create JSON readers, writers, builders, and their factory objects

JSONGenerator

Writes JSON data to a stream one value at a time

JSONReader

Reads JSON data from a stream, and creates an object model in memory

JSONObjectBuilder

Creates an object model in memory by adding values from application code

JSONArrayBuilder

Creates an array model in memory by adding values from application code

JSONWriter

Writes an object model from memory to a stream

JSONObject

Represents the JSON Object data type

JSONArray

Represents the JSON Array data type

JSONValue

Represents data types for values in JSON data

JSONNumber

Represents data types for numbers in JSON data

JSONString

Represents data types for strings in JSON data

JSONBoolean

Represents Boolean data types for TRUE and FALSE in JSON data

JSONNull

Represents the Empty data type for NULL in JSON data

The next section presents a brief overview of the JSON Streaming Model API for Oracle Java.

The JSON Streaming Model: Parser and Generator

The JSON Streaming API is a low-level API that is designed to process very large amounts of JSON data efficiently. Other JSON frameworks (such as JSON binding) can also be implemented using this API. The JSON Streaming API is similar to the StAX XML Streaming API. The JSON Streaming API consists of the Java interface JSONParser as well as the Java interface JSONGenerator.

As you may have guessed, the JSONParser interface contains methods to parse JSON data using this JSON streaming model. The JSONGenerator interface contains methods for writing JSON data stream into an output source.

The JSONParserinterface provides forward-moving, sequential, read-only access to JSON data by using the pull-parsing programming model. In this model, your application code controls the thread and calls methods in the JSONParser interface to move the parser forward sequentially or, alternately, to obtain JSON data from the current state of this parser.

The JSONGenerator interface , on the other hand, provides Java methods to write JSON data out to a datastream. This interface should be used to write your key:value pairs into JSON objects and to write sequential data values into JSON arrays. The primary Java classes and interfaces contained in the JSON Streaming API are shown in Table 5-2; note that the JSON class spans both the object and streaming models.

Table 5-2. Primary Classes and Interfaces in the Java JSON Streaming Model API

Class or Interface

Description

JSON

Contains static methods to create JSON readers, writers, builders, and their factory objects

JSONParser

Represents an event-based parser that can read JSON data from a stream

JSONGenerator

Writes JSON data to the stream one value at a time

Now that you have learned about JSON objects and arrays, you can examine the different types of data values that can be contained in these two types of JSON structures.

Summary

This chapter looked at how to define and access data arrays in JavaScript, JSON, and Java using the JSON APIs. You saw how data arrays allow you to store large collections of sequential data for applications, and how data arrays can be constructed and referenced using JavaScript, JSON, and Java. In Chapter 6, you learn about the data types and values that are allowed in JSON.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.12.180