JSON

Dr. Greg Bernstein

Updated February 5th, 2021

JSON (JavaScript Object Notation)

Learning Objectives

  • Understand that JSON is a restricted subset of JavaScript types
  • Understand and use JSON with JavaScript or almost any other programming language
  • Realize the popularity of JSON in web applications
  • Be able to use JSON format for: data storage, data transmission, configuration data, etc…

References

What is it?

JSON: JavaScript Object Notation

JSON is the the most popular general data exchange format used in modern web programming. Although the term AJAX stands for “Asynchronous JavaScript And XML” most modern web applications use JSON for these types of data exchanges.

Is it just JavaScript

Yes and No. Its a very restricted subset of JavaScript that is sufficiently powerful to model almost any data.

Essentially it is based on JavaScript objects literals, array literals, and primitive types.

Formally

From json.org

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON Object

From json.org

JSON Object

JSON Object Stricter than JS Object

  • JSON: {"course": "CS351", "numStudents": 41} Must use double quoted strings for properties

  • JavaScript: {course: "CS351", numStudents: 41} Fine in JavaScript, illegal in JSON!

JSON Array

From json.org

JSON array

JSON Value

From json.org

JSON Value

JSON String

From json.org

JSON string

JSON String Stricter than JS String

  • JavaScript has single quoted, double quoted, and back tick strings.

  • JSON only has double quoted strings!

JSON Number

From json.org

JSON number

JSON Libraries

Are available for almost all programming languages

Ada, C, C++, C#, Clojure, Cobol, Fortran, Go, Haskel, Java, JavaScript, Lisp, Lua, Perl, Python, Rust, …

You will sometimes find multiple libraries available for a language. Some are optimized for speed or size, or…

In JavaScript

From MDN JSON

  • JSON.parse(): Parse a string as JSON, optionally transform the produced value and its properties, and return the value.

  • JSON.stringify(): Return a JSON string corresponding to the specified value, …

JavaScript Example

myString = '{"name": "DrB", "class": "CS351"}'; // Strict JSON in string
thing = JSON.parse(myString)
// *thing* is a JS Object

// Start with Object
myObj = {desc: "bunch of numbers", numbers: [3, 5, 12, 8]};
myString2 = JSON.stringify(myObj); // Create String
// compare!

Importing JSON Files

  • Node.js require() of a JSON file automatically processes file into JavaScript object/array

  • In some bundlers such as parcel.js and Webpack import of a JSON file will process contents into JavaScript object/array.

// reveal.js plugins