W2271 JSON FILES

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder


What is JSON?[edit]

Javascript Object Notation or JSON is a text-based, language-independent, data-interchange format that is in a similar category to XML or YAML. Although JSON can be used with almost every major coding language, JSON wouldn't be correctly classified as a "programming language," per se. Rather, it is a text-based, open-standard method of storing, sending, and retrieving data between a client and server. JSON is a very important data representation format because it is widely used to perform most web-based API calls. It is very common in facilitating communication between servers and clients in many applications. When using JSON in Swift, you can think of JSON as a dictionary that maps keys to unique values. These values can be strings, numbers, bools, or null (nothing). As an iOS developer early in your career, it is very important to learn JSON. You will come across it quite often when building applications that interact with web services. For example, major web platforms such as Facebook and Twitter use JSON to transmit data to and from your application.

JSON example[edit]

{"Teammates":[
  { "firstName":"LeBron", "lastName":"James" },
  { "firstName":"Kobe", "lastName":"Bryant" },
  { "firstName":"Michael", "lastName":"Jordan" }
]}

What is the motivation for learning JSON?[edit]

A developer might want to learn JSON for several reasons. First: as a lightweight, text-based, data-integer format, JSON is very intuitive. This makes it relatively easy to become fluent in JSON in a short time.

Second: because is it derived from JavaScript notation and syntactically similar to JavaScript, it is very easy for JavaScript compilers to compile JSON and to convert JSON to and from JavaScript objects. This makes it extremely easy to use JSON to transmit data within web applications, such as sending data to and from a server and a client. If you are familiar with JavaScript, you will have an immediate head start in learning JSON.

Third: JSON is an independent data-integer format. This means that nearly every major coding language has a JSON library. This allows JSON to be injected and interpreted by compilers, independent of the coding language you are using.

What are the benefits and shortcomings of JSON?[edit]

Let's explore some of the primary benefits and shortcomings of JSON because it will most certainly come up in your day-to-day coding practices. And to better frame a convincing argument for the advantages and disadvantages of JSON, it is important to define what we are comparing JSON against. Today, as you may know, several other comparable lightweight human-readable data-interchange formats are used. Some of the closest apples-to-apples comparisons are XML and YAML. To highlight some of the advantages and disadvantages of JSON, let's take a look at how JSON compares to some of the other common toolsets in this category.

Benefits of JSON[edit]

Let's start with some of the advantages as to why a developer might choose JSON over any other similar text-based data-interchange format.

1. Easily Readable. One of the strongest benefits of JSON is its readability. To humans, JSON is readable and intuitive. And to compilers, JSON easily interpreted via a parsed string. This gives it a big advantage over other comparable data-interchange formats.

2. Compact. The JSON syntax is very compact and efficient. This makes it easy to write in a condensed format, supporting easy data parsing.

3. Widely Supported. JSON is widely supported by most coding language compilers, browsers, and operating systems. This makes it easy to use JSON with very few compatibility concerns.

Shortcomings of JSON[edit]

Even with its flexibility, readability, and wide adoption among coding languages, JSON has several shortcomings.

1. Lack of Standards. Unfortunately, JSON lacks a set of universal release standards. This has led to incompatible JSON versions.

2. Lack of Robustness. As an easy-to-write, text-friendly format, JSON lacks some robustness. JSON has no ability for you to annotate data structure or add metadata to JSON text.

3. Dangerous with Untrusted Service. The JSON service return from web services is wrapped in a JSON function call. There is no oversight in the trust of the browser or web service JSON data is being transmitted over. This can unintentionally expose a vulnerability.

JSON vs. XML[edit]

Today, nearly every computer application and web service uses either JSON or XML because they are today's most popular toolsets to facilitate server-to-client communication. Much like JSON, XML (or Extensible Markup Language) is a hardware-independent markup language used for transmitting and storing data, is fairly easy for humans to read, and can be compiled in many different coding language compilers. Today, JSON dominates the coding space; it has overtaken XML in the past 5 years. Because JSON and XML are the most ubiquitous coding toolsets in this category, it is important to understand some of the similarities and differences between these two tools.

Similarities between JSON and XML[edit]

Although JSON and XML differ quite a bit from one another, they are often compared because of a few core similarities. Much like JSON, XML is easily legible for humans with the intention to store and transfer data via APIs and various coding languages. And because one of the primary use cases for both JSON and XML is to transmit data via web services, they can both be fetched by an XHR—or XMLHttpRequest. An XHR is an API that is available in scripting languages such as JavaScript, Python, PHP, Ruby, and others, and its object enables you to request data from a web server.

Differences between JSON and XML[edit]

Despite having very similar purposes, some critical differences exist between JSON and XML. Distinguishing these differences can help you understand which is the best choice depending on the needs of a project.

First, one of the most significant advantages of using JSON is that the file size is smaller; thus, transferring data is faster than XML. Moreover, since JSON is compact and very easy to read, the files look cleaner and more organized without empty tags and data. The simplicity of its structure and minimal syntax makes it easier for humans to use and read JSON. In contrast, XML is often characterized for its complexity and old-fashioned standard because of the tag structure that makes files bigger and harder to read.

However, JSON vs. XML is not entirely a fair comparison. JSON is often wrongly perceived as a substitute for XML. Whereas JSON is a great choice to make simple data transfers, it does not perform any processing or computation. XML might be "old" and complex, but its complexity is what enables it to transfer data and to process and format objects and documents.

10 Key Differences between JSON and XML[edit]

  • JSON object has a type; XML data is typeless
  • JSON has a "Data interchange" file format; XML has a "Markup Language" file format
  • JSON types include string, number, array, and Bool; XML stores data only as a string
  • JSON is supported by all popular browsers; cross-browser XML is challenging
  • JSON supports characters and numbers; XML supports text, images, and other assets
  • JSON is less complex, so it is easier to learn and understand than XML
  • JSON is data-oriented; XML is document-oriented
  • JSON supports the array data structure; XML does not
  • JSON is less secured than XML
  • JSON files are more human-readable than XML

Coding Comparisons for JSON and XML[edit]

JSON

{"classmates":[
  { "firstName":"Bob", "lastName":"Smith" },
  { "firstName":"Joe", "lastName":"Brown" },
  { "firstName":"Don", "lastName":"Miller" },
  { "firstName":"Pete", "lastName":"Tyson" }
]}

XML

<Classmates>
  <classmates>
    <firstName>Bob</firstName> <lastName>Smith</lastName>
  </classmates>
  <classmates>
    <firstName>Joe</firstName> <lastName>Brown</lastName>
  </classmates>
  <classmates>
    <firstName>Don</firstName> <lastName>Miller</lastName>
  </classmates>
  <classmates>
    <firstName>Pete</firstName> <lastName>Tyson</lastName>
  </classmates>
</classmates>

JSON in Swift[edit]

A very strong use case is made for JSON when working in Swift. For example, if you are working on an app that must transmit data to and from a web service via an API. Every time you want to send or receive data to and from this web service, your Swift code must be encoded to and from JSON to enable this communication. This is one of JSON's most profound capabilities. With it, you can encode any data format in JSON, and decode JSON back to any data format by using some predefined protocols.

This built-in support for translating code to and from JSON and Swift is known as codable. When a piece of JSON code is considered codable, it becomes very simple and straightforward to freely convert data into usable Swift code. These protocols come in handy for sending and storing data with JSON.

Once a Swift object is defined as "codable," you can then easily encode and decode it to facilitate API-based transmission to web services.

  • Encodable. When a piece of JSON code is encodable, you're signifying that this data can be converted to a JSON object. Most commonly, this is used to send data to the server.
  • Decodable. By marking your model type as decodable, you're signifying that this JSON object can be converted to a Swift value. Most commonly, this is used when receiving data from the server.

Before digging into some of the Swift protocols, let's start with a simple example of a JSON object with five keys. For this example, let's assume you're working on an app that uses professional athletes' stats.

You might have a Swift object that follows the given structure:

struct Player Codable {
    var name: String
    var position: String
    var url: URL
    var number: Int
    var bio: String
}

And to show how to translate data between Swift and JSON, let's write some accompanying JSON.

{
    "name":     "LeBron James",
    "position":   "Shooting Guard",
    "url":      "https://www.nba.com/player/2544/lebron-james",
    "number":    6,
    "bio": "Four-time NBA Champion (2012, 2013, 2016, 2020) … Four-time NBA Most Valuable Player (2009, 2010, 2012, 2013) … Four-time NBA Finals MVP 
     (2012, 2013, 2016, 2020)",
}

Because JSON data is typically received and sent by web service APIs as a string, let's go one step further to translate this JSON text into a string.

let jsonString = """
{
    "name":     "LeBron James",
    "position":   "Shooting Guard",
    "url":      "https://www.nba.com/player/2544/lebron-james",
    "number":    6,
    "bio": "Four-time NBA Champion (2012, 2013, 2016, 2020)  Four-time NBA Most Valuable Player (2009, 2010, 2012, 2013)  Four-time NBA Finals MVP 
     (2012, 2013, 2016, 2020)",
}
"""

Once a JSON string is created, you can start by converting this JSON string to a user object, a critical step to begin using the decoder and encoder protocols.

let jsonObject = jsonString.data(using: .utf8)!

Now, by using JSONDecoder, we can create a new object as such:

let player = try! JSONDecoder().decode(User.self, from: jsonObject)
print(player.position)
// Output: Shooting Gaurd

JSON Decoder Example[edit]

CoderMerlin™ Code Explorer: W0000 (3)


JSON Encoding[edit]

CoderMerlin™ Code Explorer: W0000 (1)


Using JSON with JavaScript[edit]

Working with JSON and JavaScript can be quite easy. In fact, you can use a set of JavaScript functions to parse JSON into a JavaScript object.

With JSON.parse(), for instance, you can input a JSON string and parse the text into a JavaScript object.

'{"name":"Bob", "age":20, "city":"Phoenix"}'

Using the JSON.parse() function, you can pass the JSON to the function as follows:

const obj = JSON.parse('{"name":"Bob", "age":20, "city":"Phoenix"}');

By doing this, JSON.parse() creates a JavaScript object, in this case a const type object called "obj", to show the JSON values in a JavaScript JSON format.

Next, using the JSON.stringify() function, the object created via the JSON text using JSON.parse() is converted to a string.

const obj = {name: "Bob", age: 20, city: "Phoenix"};

Again, this results in a const type object with the given values. And now, that object can be converted to a string.

const myJSON = JSON.stringify(obj);

Quiz[edit]

1 The proper way an object should be enclosed in JSON is:

{}
()
[]
None of these

2 By assigning JSON data to a JavaScript variable, the JSON data becomes a/an:

Callback function
Function
Alert
Object

3 JSON stands for

Java Standard Output Network
Java Source Open Network
JavaScript Object Notation
JavaScript Output Name

4 What is the correct syntax for writing a JSON name/value pair?

"name" : "value"
'name : value'
name = 'value'
name = "value"

5 Which of the following is not a type in JSON?

string
Array
date
Object

6 What extension is used to save a JSON file?

.xsl
.json
js
xml

7 Is JSON case sensitive ?

Yes
No

8 What are two main structures that compose JSON?

Arrays and objects
None of the above
Keys and values
Class and objects

9 What is the common use of JSON on modern websites?

To store information locally
To store information remotely
To send and receive bits of data
All the above

10 JSON elements are separated by the ___.

white space
line break
semicolon
comma