W2271 JSON FILES

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

What is JSON?[edit]

JSON or Javascript Object Notation 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 webservice uses either JSON or XML as these 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, having overtaken XML within the last 5 years. Since JSON and XML are the most ubiquitous coding toolsets in this category, it's important to understand some of the similarities and differences that differentiate these two tools.

Similarities between JSON and XML[edit]

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

Differences between JSON and XML[edit]

Despite resolving very similar purposes, there are some critical differences between JSON and XML. Distinguishing these differences can help a developer understand which is the best alternative according to specific 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 JSON easier to be used and read by humans. Contrarily, XML is often characterized for its complexity and old-fashioned standard due to 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, but while 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 this language to not only transfer data but also to process and format objects and documents.

10 Key Differences Between JSON and XML[edit]

  • JSON object has a type whereas XLM data is typeless
  • JSON has a “Data interchange” file format, whereas XML has a “Markup Language” file format.
  • JSON types include string, number, array and Bool whereas, XML only stores data as a string
  • JSON is supported by all popular browsers, whereas cross-browser XML is challenging
  • JSON supports characters and numbers, whereas XML supports text, images and other assets
  • JSON complexity level regarding learning and understanding is easier than XML.
  • JSON is data-oriented, whereas XML is document-oriented.
  • JSON supports the array data structure, whereas XML does not.
  • JSON is less secured compared to XML.
  • JSON files are more human-readable than their counterpart XML.

Coding Comparisons for JSON and XML[edit]

{"classmates":[
  { "firstName":"Bob", "lastName":"Smith" },
  { "firstName":"Joe", "lastName":"Brown" },
  { "firstName":"Don", "lastName":"Miller" },
  { "firstName":"Pete", "lastName":"Tyson" }
]}
<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]

There's a very strong use case for considering JSON when working in Swift. Take for example, if you are working on an app that is required to transmit data to and from a webservice via API. Every time you wish to send or receive data to and from this webservice, your Swift code must be encoded to and from JSON to facilitate this communication. This is one of JSON's most profound capabilities. With JSON developers are able to encode any data format in JSON, and decode JSON back to any data format, simply 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, developers can freely convert data into usable swift code in a very simple and straightforward manner. Importantly, these protocols come in very handy for sending and storing data with JSON.

And once a Swift object is defined as "Codable" it can then be easily encoded and decoded to facilitate API-based transmission to webservices.

  • 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. And for means of example, let's assume you're working on an app that uses professional athletes' stats in some facet.

You may 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)",
}

Since JSON data is typically received and sent by webservice APIs as a string, let's to 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, developers 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, there are a series of Javascript functions that can be called to parse JSON into a Javascript object.

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

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

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

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

By doing so, JSON.parse() will create a Javascript object, in this case, a const type object called obj to how the JSON values in a Javascript JSON format.

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

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

Again, 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 propper 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:

Object
Callback function
Function
alert

3 JSON stands for

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

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
Object
date
Array

6 What extension is used to save a JSON file?

.json
js
xml
.xsl

7 Is JSON Case sensitive ?

No
Yes

8 What are two main structures compose JSON?

Keys and values
None of above
Arrays and Objects
Class and Objects

9 What is the common usage of Json on modern websites?

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

10 JSON elements are separated by the ___.

line break
comma
white space
semi-colon