Difference between revisions of "W2271 JSON FILES"

From Coder Merlin
Line 37: Line 37:
'''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''' - 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.
'''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==
==JSON vs. XML==

Revision as of 02:27, 23 November 2021

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

What is the motivation for learning JSON?[edit]

JSON has several major benefits that provide a motivation 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 is JSON?[edit]

 This article can be improved by:  Adding new words to the glossary and adding references (e.g. XML, YAML). See StandardMarkup#Glossary.

JSON or Javascript Object Notation is a text-based language-independent data-interchange format very 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 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.

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

Since JSON commonly serves as a data-interchange language and is used in high frequency with Swift applications that leverage API-based webservices, let's explore some of the major benefits for knowing JSON as you develop your coding career, and some disadvantages as well.

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 competing 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 these compare and uncover 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 passed strings 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 and 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.

4. Flexible - JSON can be easily converted from a text-based string to an object and vice versa very easily. This makes JSON very flexible when developers look to use JSON interchangeably with other coding languages, or applications.

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 wary 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]

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 jsondecoder = JSONDecoder()

Now that the decoder object is created, it's now possible to decode the JSON data as follows:

let user = try! decoder.decode(User.self, from: jsonData)


JSON Encoding[edit]

Does not compile

CoderMerlin™ Code Explorer: W0000 (1) 🟢


JSON Decoding[edit]

Does not compile

CoderMerlin™ Code Explorer: W0000 (2) 🟢


Using JSON with JavaScript[edit]

Converting JSON to Javascript is quite easy. 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.

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