Keywords

These keywords were added by machine and not by the authors. This process is experimental and the keywords may be updated as the learning algorithm improves.

Now that you have had an overview of the integrated development environment (IDE) you use to work with JSON and compatible OOP languages—the most common of which is Oracle NetBeans 8.1 for Java, JavaFX, and HTML5 development—this chapter takes a high-level look at what defines JSON, including the concepts behind it, advantages of using JSON, terms used to describe it, and the various rules that dictate its data-object definition design approach. JSON is well on its way to replacing XML as a definition format, at least where object-oriented data is concerned. Chapter 3 looks at object-oriented concepts and design; here you focus on learning other JSON-related information, so later you can focus on the definition format and what it supports and allows you to do with objects. After these core chapters, the book examines real-world applications for JSON as well.

What Is JSON?

J SON stands for JavaScript Object Notation. It is based on the ECMA-262 3rd Edition JavaScript Standard established in December 1999. This subset of the JavaScript programming language, often called ECMAScript , is what I use for JavaScript programming. This is so my JavaScript code is sure to run across all WebKit-based HTML5 browsers and HTML5 operating systems. This is why I use ECMAScript in my HTML5 with CSS3 and JavaScript projects, rather than one of the proprietary JS package solutions (Node.JS, for instance), which might not have native support on any given OS, platform, or device. To have native support, the Node.JS library would have to be part of an OS, browser, or platform API, as ECMAScript-262 is. More about this later on in the chapter. Let’s look at JSON’s advantages.

JSON Is Lightweight: Simpler Is Usually Superior

The JSON object structure definition language originally was designed and developed for use as a lightweight, JavaScript object-oriented data-interchange programming structure. This JSON format was specifically designed to be as simple as possible so that programmers can read JSON data structures effortlessly as well as encode JSON data structures optimally, concisely, quickly, and efficiently.

Obviously, this also makes JSON easy for programming algorithms to parse, process, and generate; but then again, what streamlined algorithm can’t a 2 GHz, multicore processor handle these days? Still, the less processing power is used to parse and process JSON data structures, the more is left over for your application to use.

No matter how powerful a server, network, or client-side device may be, data-footprint optimization is always a great thing. You want scalability to be maximized in case your application takes off and millions of users flock to it as it becomes the “in thing.” This is exactly what JSON has been optimized for in its design, structure, language, and implementation. XML, for instance, uses far more characters to design data structures than a JSON structure would.

JSON Is Text-Based: 100% Language Independent

JSON uses a text-based format that’s completely language independent. The specification uses conventions familiar to programmers of OOP languages, including C, C+, C++, Objective-C, C#, Java, JavaFX, JavaScript, Ruby, Visual Basic .NET, Object COBOL, Object Pascal, Scala, Smalltalk, ADA, Perl, PHP5, Python, Prolog, and dozens of others. (In case you are wondering, Simula was the first OOP language; it was created in Norway by Ole-Johan Dahl and Kristen Nygaard back in the 1960s. The creator of C++, Bjarne Stroustrup, was influenced by the object-based approach of Simula. The Java programming language was also influenced by this object-oriented approach.)

This object-based, text-scripted approach makes JSON the perfect data-interchange definition language for use in today’s popular OOP languages, operating systems, devices, and platforms. Let’s take a closer look at the types of data structures that can be used in a JSON data-definition language construct. After that, you explore the close relationship JSON has with ECMAScript-262 JavaScript as its primary parsing OOP language.

JSON Structures: Data Objects and Data Arrays

Only two primary types of data structures can be used in JSON, and they’re covered in this section. This doesn’t mean JSON data constructs are not powerful; these two types of data structures can be used in conjunction to build complex data representations, as you see throughout this book.

It is important to note that the structures used in JSON are what are called universal data structures, because they are used in virtually all current programming languages and platforms in one format or another. It is therefore logical that JSON is based on these two types of data structures, in order for each language that supports using JSON to be able to parse, or deconstruct, JSON representations into objects in memory.

Data Objects: Collections of Name:Value Pairs for Data Structures

A collection of name:value pairings is known across programming languages by a many terms. The most common is object, due to C++ and Java, but terms such as record, from database languages; struct, for structure (which I prefer); and hash table are also common, as you know. Other terms include associative array, data dictionary, and keyed list.

Thanks to the curly brace { ... } encapsulation construct and the ability to nest these constructs, objects can become complex and powerful for defining precise data-structure organization and object-design hierarchies. You look at this in Chapter 3, which reviews OOP concepts, structure, and terminology using the popular Java and JavaScript languages.

Data Arrays : An Ordered List Defining Sequential Data Values

In addition to data objects, you can also define data arrays, which are ordered lists of data values that can be accessed by positional pointers or references in that sequence. This is a database or datastore in its simplest format. In conjunction with the allowed object structure, your database record structure can be simulated handily using JSON.

An ordered list of sequential data values is also recognized across programming languages by a number of terms. This construct is most commonly referred to as a data array. Other terms, such as vector, from 2D and 3D mathematics; sequence, also from mathematics; and list are also common. Other terms may include data collection, datastore, and ordered data.

JSON Is JavaScript Compatible: Easy Integration

Because JavaScript is half of what JSON stands for, it is logical that JSON works seamlessly with JavaScript (JS). JavaScript is a general-purpose programming language originally introduced with the Netscape Navigator browser, as its document scripting language. JavaScript works in conjunction with HTML5 and CSS3. One of the popular myths regarding JavaScript is that it is somehow related to Oracle’s Java, but it is in fact not related to Java other than being another popular OOP language. JavaScript has been standardized in ECMAScript using the ECMAScript-262 Language Specification, 3rd Edition.

JavaScript is similar to the Scheme language and uses a syntax much like the original C programming language. It uses soft objects , where new object members can be added to the soft object via simple assignment. A hard object , on the other hand, would require a new class to instantiate it. You look at this difference in more detail in Chapter 3.

JSON is a subset of JavaScript’s object literal notation and is therefore seamlessly compatible using that OOP language. Because JSON is a subset of JavaScript, it can be used in that language with no alteration of format, structure, or code design. This means less work for the JavaScript (HTML5) developer.

JSON object members can be retrieved in JavaScript using dot notation (object.member) or subscript operators, so you can reference members in the JSON defined object right in the JavaScript code. You can also convert JSON object definitions to JavaScript objects using the JS eval() function.

Converting a JSON Object Definition to an Object: Using eval( )

To convert JSON text to an object in JavaScript, you can use a JavaScript eval() function. The eval() function invokes the JavaScript compiler. Because JSON is a subset of JavaScript, your compiler will correctly parse the JSON object definition text, produce that object’s structure, and load it in system memory. The JSON object definition must be wrapped in parentheses to avoid triggering any code ambiguities when you are compiling JavaScript syntax. The JavaScript syntax looks like this:

var yourJSONobject = eval(' (' + yourJSONobjectDefinition + ') ');

The algorithm used by JavaScript’s eval() function is well optimized, so it executes very rapidly. The eval() function can also compile and execute other JavaScript programs, so security issues may arise. Therefore, if you’re going to use an eval() function, make sure your source is trusted and the programmers who wrote the source were competent.

If your web application is using an XMLHttpRequest call, communication is allowed only via the same server providing the page. This determines that it’s trusted. However, that source JSON object definition may still be incompetent. If your server is not robust in its JSON encoding, or if it does not meticulously validate all of its data input, then it could deliver invalid JSON object definition text that may carry dangerous script. An eval() function might execute this scripting and unleash malware.

Parsing JSON Object Definitions into Objects: Using JSON.parse( )

Because of the security issue with the eval() function, it is safer to use the JSON parser. The JSON parser recognizes only JSON object definitions, rejecting other scripts that do not define properly formed JavaScript Object Notation.

In HTML5 browsers that provide native JSON support, the JSON parser approach should be significantly faster than using the eval() function. Native JSON support is included in the sixth ECMAScript standard, also called the ECMAScript 2015 Language Specification. A PDF of the specification can be found at http://www.ecma-international.org/ecma-262/6.0/ECMA-262.pdf .

Using JSON.parse() on the JSON definition looks like this:

var yourJSONobject = JSON.parse(yourJSONobjectDefinition, reviver);

The (optional) reviver parameter can contain a function, which is called for every key:value pair at every level of the final object. Each value is replaced by the result of this reviver function. The reviver function may be used to reform generic objects to pseudoclass instances or, for instance, to transform any date strings into actual Date objects with a Date function.

There is also a JSON.stringify() function, if you want to go in the other direction and turn your JavaScript objects into JSON definitions. This function, like JSON.parse(), is included in the ECMAScript 2015 Language Specification. Let’s take a look at this JavaScript function next.

Stringifying JSON Objects into Definitions: Using JSON.stringify( )

The JSON.stringify() function lets you process in the opposite direction and convert JavaScript object structures into JSON definitions. Because JSON does not support cyclical data structures, be careful not to give any cyclical data structures to a JSON stringifier. Using JSON.stringify() on your JSON object looks like this:

var yourJSONobjectDefinition = JSON.stringify(yourJSONobject, replacer);

If the stringify() method encounters any JavaScript object that contains a toJSON() method, it calls that method. This stringifies the value that is returned, whch should allow the object to determine its own JSON representation.

The JSON.stringify() method can take an (optional) array of strings. These strings are used to select the properties that are included in the JSON object definition’s text.

The JSON.stringify() method can also take the (optional) replacer function. This is called only after the toJSON() method, if there is one present, on each of the values in your object data structure. This is passed each key:value pair as parameters and is bound to the object holding the key. The returned value is stringified.

Values that don’t have any representation in JSON, such as functions and undefined, are excluded. Nonfinite numbers are replaced with a null value. To substitute other values, you should use the replacer function.

A customized replacer(key, value) function is coded something like this in JavaScript:

function replacer(key, value) {     if (typeof value === 'number' && !isFinite(value)) {         return String(value);     }     return value; }

Giving your corresponding reviver to JSON.parse() can undo the replacer function, so these are analogs (opposites) of each other.

JSON.parse( ) and JSON.stringify( ) : Open Source Code Available

The open source code for a JSON parser or a JSON stringifier is available at creator Douglas Crockford’s GitHub account https://github.com/douglascrockford/JSON-js . There are cycle.js utilities for JSLint, JSON_Parse, and JSON2.js functions available. When minified, these are less than 2.5 KB.

JSON became a built-in feature of JavaScript when the ECMAScript-262 5th Edition was adopted in 2009.Most of the files on this web site are for applications that are expected to run in deprecated (obsolete) web browsers. For most purposes, you should use the JSON2.js version or functions that are native to the latest ECMAScript version.

JSON Open Licensing: Free for Commercial Use

JSON has an exceptionally open license , which I copied from the popular www.json.org website and included here for review. As you see, you must always include this licensing text.

JSON LICENSE Copyright (c) 2002 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Summary

This chapter defined what JSON is, its advantages and attributes, concepts and terminology, and so forth, to give you a broad foundational understanding of JSON before the rest of the book starts breaking it down into its logical components. In the Chapter 3, you learn about OOP languages with an object-orientation primer (review), before the book gets into defining JSON objects and taking a look at how to create a JSON object definition.