From Coder Merlin

What is JSON?[edit]

JSON or Javascript Object Notation is a text-based language-independent data-interchange format that is categorically similar 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’s 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, as it is widely used to facilitate the majority of web-based API calls and is very common in facilitating communication between servers and clients in a wide array of applications. When it comes to 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). And for that iOS developer early in their career, it's very important to consider learning JSON as you'll come across it quite often when working building applications that interact with webservices. For instance, major web platforms such as Facebook to Twitter, use JSON to transmit data to and from your application.

JSON example[edit]

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

What is the motivation for learning JSON?[edit]

There are several reasons why a developer may want to learn JSON. First off, as a lightweight text-based data-integer format, JSON is very intuitive, making it relatively easy to become fluent in JSON in a short amount of time. Secondly, being derived from JavaScript notation and syntactically similar to JavaScript, it's very easy for JSON to be complied by JavaScript compilers and to convert JSON to and from javascript objects. This makes it extremely easy to leverage JSON to transmit data within web applications, such as sending data to and from a server and a client. That said, those who are familiar with JavaScript will have an immediate leg up in learning JSON. JSON is also an independent data-integer format, meaning that nearly every major coding language today has a JSON library allowing JSON to be injected and interpreted by compliers independent of the coding language you wish to write in.

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

Let's explore some of the primary benefits and shortcomings of JSON since 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's important to define what we are comparing JSON against. Today, as you may know, there are several other comparable lightweight human-readable data-interchange formats. Some of the closest apples-to-apples comparisons are XML and YAML. Let's take a look at how JSON compares to some of the other common toolsets in this categorization to highlight some of the advantages and disadvantages of JSON.

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 compliers, JSON easy interpreted via a parsed string, giving it a big advantage over other comparable data-interchange formats.

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

3. Widely Supported - JSON is widely supported by most coding language compilers, browsers and operating systems, making 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, there are in fact several shortcomings of JSON to be aware of.

1. Lack of Standards - Unfortunately, JSON lacks a set of universal release standards that have led to incompatible JSON versions.

2. Lack of Robustness - JSON being an easy-to-write text-friendly format, lacks some robustness. With JSON, there is no ability to annotate data structure or add metadata to JSON text.

3. Dangerous with Untrusted Service - The JSON service return from webservices is wrapped in a JSON function call, there is no oversight in the trust of the browser or webservice 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]

  { "firstName":"Bob", "lastName":"Smith" },
  { "firstName":"Joe", "lastName":"Brown" },
  { "firstName":"Don", "lastName":"Miller" },
  { "firstName":"Pete", "lastName":"Tyson" }
    <firstName>Bob</firstName> <lastName>Smith</lastName>
    <firstName>Joe</firstName> <lastName>Brown</lastName>
    <firstName>Don</firstName> <lastName>Miller</lastName>
    <firstName>Pete</firstName> <lastName>Tyson</lastName>

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)
// 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);


1 == Qui z == <quiz shuffleanswers=true display=simple> { 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:

Callback function

3 JSON stands for

JavaScript Object Notation
Java Source Open Network
Java Standard Output Network
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?


6 What extension is used to save a JSON file?


7 Is JSON Case sensitive ?


8 What are two main structures compose JSON?

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

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

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

10 JSON elements are separated by the ___.

line break
white space

CoderMerlin™ proudly recommends:

Your purchase via these links helps keep  Coder Merlin™ 's orbuculum ablaze. As an Amazon Associate we earn from qualifying purchases. Thank you for your support!

Designed with pride in Silicon Valley, CA, USA