Difference between revisions of "W2271 JSON FILES"

From Coder Merlin
 
(41 intermediate revisions by 2 users not shown)
Line 1: Line 1:
==What is JSON?==
==What is JSON?==
'''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.
'''Javascript Object Notation''' or {{GlossaryReference|JSON|JSON}} is a text-based, language-independent, data-interchange format that is in a similar category to {{GlossaryReference|XML|XML}} or {{GlossaryReference|YAML|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====
====JSON example====
<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
Line 11: Line 11:


==What is the motivation for learning JSON?==
==What is the motivation for learning JSON?==
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.
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.
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.
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?==
==What are the benefits and shortcomings of JSON?==
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.
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===
===Benefits of JSON===
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.  
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.
'''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, making it easy to write in a condensed format, supporting easy parsing of data.
'''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, making it easy to use JSON with very few compatibility concerns.
'''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===
===Shortcomings of JSON===
Even with its flexibility, readability and wide adoption among coding languages, there are in fact several shortcomings of JSON to be aware of.
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 that have led to incompatible JSON versions.
'''1. Lack of Standards'''. Unfortunately, JSON lacks a set of universal release standards. This has 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.
'''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 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.
'''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==
==JSON vs. XML==
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.
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===
===Similarities between JSON and XML===
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.
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===
===Differences between JSON and XML===
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.
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 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.
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, 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.
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====
====10 Key Differences between JSON and XML====
*JSON object has a type whereas XLM data is typeless
*JSON object has a type; XML data is typeless
*JSON has a “Data interchange” file format, whereas XML has a “Markup Language” file format.
*JSON has a "Data interchange" file format; XML has a "Markup Language" file format
*JSON types include string, number, array and Bool whereas, XML only stores data as a string
*JSON types include string, number, array, and Bool; XML stores data only as a string
*JSON is supported by all popular browsers, whereas cross-browser XML is challenging
*JSON is supported by all popular browsers; cross-browser XML is challenging
*JSON supports characters and numbers, whereas XML supports text, images and other assets
*JSON supports characters and numbers; XML supports text, images, and other assets
*JSON complexity level regarding learning and understanding is easier than XML.
*JSON is less complex, so it is easier to learn and understand than XML
*JSON is data-oriented, whereas XML is document-oriented.
*JSON is data-oriented; XML is document-oriented
*JSON supports the array data structure, whereas XML does not.
*JSON supports the array data structure; XML does not
*JSON is less secured compared to XML.
*JSON is less secured than XML
*JSON files are more human-readable than their counterpart XML.
*JSON files are more human-readable than XML


===Coding Comparisons for JSON and XML===
===Coding Comparisons for JSON and XML===


====JSON and XML Comparison====
JSON
 
<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
{"classmates":[
{"classmates":[
Line 74: Line 75:
</syntaxhighlight>
</syntaxhighlight>


XML
<syntaxhighlight lang="XML">
<syntaxhighlight lang="XML">
<Classmates>
<Classmates>
Line 92: Line 94:


==JSON in Swift==
==JSON in Swift==
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.  
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, 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.
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.


And once a Swift object is defined as "Codable" it can then be easily encoded and decoded to facilitate API-based transmission to webservices.
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.
* '''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.  
* '''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.
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 may have a Swift object that follows the given structure:
You might have a Swift object that follows the given structure:


<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
Line 129: Line 131:
</syntaxhighlight>
</syntaxhighlight>


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.
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.


<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
Line 144: Line 146:
</syntaxhighlight>
</syntaxhighlight>


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.
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.


<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
Line 153: Line 155:


<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
let jsondecoder = JSONDecoder()
let player = try! JSONDecoder().decode(User.self, from: jsonObject)
print(player.position)
// Output: Shooting Gaurd
</syntaxhighlight>
</syntaxhighlight>


Now that the decoder object is created, it's now possible to decode the JSON data as follows:
==JSON Decoder Example==
 
<syntaxhighlight lang="swift">
let user = try! decoder.decode(User.self, from: jsonData)
</syntaxhighlight>
 
==JSON Encoding==
{{MerlinErrorFromEditor|Does not compile}}
{{CodeExplorer
{{CodeExplorer
|exerciseID=1
|exerciseID=3
|mode=swift
|language=swift
|height=400
|height=400
|initialCode=import Foundation
|initialCode=import Foundation


let player = Player()
struct User: Codable {
let encoder = JSONEncoder()
    var first_name: String
    var last_name: String
    var country: String
}
 
let jsonString = """
{
    "first_name": "John",
    "last_name":  "Doe",
    "country":    "United Kingdom"
}
"""




guard let data = try? encoder.encode(board),
let jsonData = jsonString.data(using: .utf8)!
      let json = String(data: data, encoding: .utf8) else {
let user = try! JSONDecoder().decode(User.self, from: jsonData)
    fatalError("Failed to encode data into json.")
print(user.first_name, user.last_name, user.country)
}
print(json)


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


== JSON Decoding ==
==JSON Encoding==
{{MerlinErrorFromEditor|Does not compile}}
{{CodeExplorer
{{CodeExplorer
|exerciseID=2
|exerciseID=1
|mode=swift
|language=swift
|height=400
|height=400
|initialCode=import Foundation
|initialCode=import Foundation


let jsonString = """
struct User: Codable {
{
     var first_name: String
     "name":     "LeBron James",
     var last_name: String
     "position":   "Shooting Guard",
     var country: String
     "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)",
}
}
"""
let decoder = JSONDecoder()


guard let data = json.data(using: .utf8),  
let person = User(first_name: "John", last_name: "Doe", country: "United Kingdom")
      let player: Player = try? decoder.decode(Player.self, from: data) else {
 
    fatalError("Failed to create player.")
let encoder = JSONEncoder()
}
encoder.outputFormatting = .prettyPrinted
dump(player)


let data = try encoder.encode(person)
print(person.first_name, person.last_name, person.country)


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


==Using JSON with JavaScript==
==Using JSON with JavaScript==
Converting JSON to Javascript is quite easy. {{MerlinErrorFromEditor|JSON is not converted to 'Javascript'.}} In fact, there are a series of Javascript functions that can be called to parse JSON into a Javascript object.
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, developers can input a JSON string and parse the text into a Javascript object.  
With '''JSON.parse()''', for instance, you can input a JSON string and parse the text into a JavaScript object.  


<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
Line 236: Line 221:
</syntaxhighlight>
</syntaxhighlight>


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


<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
Line 242: Line 227:
</syntaxhighlight>
</syntaxhighlight>


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.
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()''' can be converted to a string.  
Next, using the '''JSON.stringify()''' function, the object created via the JSON text using '''JSON.parse()''' is converted to a string.  


<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
Line 250: Line 235:
</syntaxhighlight>
</syntaxhighlight>


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


<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
const myJSON = JSON.stringify(obj);
const myJSON = JSON.stringify(obj);
</syntaxhighlight>
</syntaxhighlight>
== Quiz ==
<quiz shuffleanswers=true display=simple>
{
The proper way an object should be enclosed in JSON is:
|type="()"}
+ {}
- []
- None of these
- ()
{
By assigning JSON data to a JavaScript variable, the JSON data becomes a/an:
|type="()"}
- Function
+ Object
- Alert
- Callback function
{
JSON stands for
|type="()"}
- Java Standard Output Network
- JavaScript Output Name
+ JavaScript Object Notation
- Java Source Open Network
{
What is the correct syntax for writing a JSON name/value pair?
|type="()"}
- 'name : value'
- name = "value"
- name = 'value'
+ "name" : "value"
{
Which of the following is not a type in JSON?
|type="()"}
- Object
- Array
- string
+ date
{
What extension is used to save a JSON file?
|type="()"}
- js
- .xsl
+ .json
- xml
{
Is JSON case sensitive ?
|type="()"}
+ Yes
- No
{
What are two main structures that compose JSON?
|type="()"}
- Arrays and objects
+ Keys and values
- Class and objects
- None of the above
{
What is the common use of JSON on modern websites?
|type="()"}
+ To send and receive bits of data
- To store information remotely
- To store information locally
- All the above
{
JSON elements are separated by the ___.
|type="()"}
- line break
- semicolon
+ comma
- white space
</quiz>

Latest revision as of 23:04, 23 January 2023

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:

Function
Alert
Callback function
Object

3 JSON stands for

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

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?

Array
date
string
Object

6 What extension is used to save a JSON file?

.xsl
js
xml
.json

7 Is JSON case sensitive ?

Yes
No

8 What are two main structures that compose JSON?

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

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

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

10 JSON elements are separated by the ___.

line break
comma
semicolon
white space