© Jesse Feiler 2018
Jesse FeilerBeginning Reactive Programming with Swifthttps://doi.org/10.1007/978-1-4842-3621-5_3

3. Reading and Writing JSON Data

Jesse Feiler1 
(1)
Plattsburgh, New York, USA
 

The building blocks discussed in this book almost all provide ways of sharing functionality across apps and often across platforms, as is the case with Facebook, Amazon Web Services, and reactive programming. This part of the book is different because it focuses on components and building blocks that let you share data across apps and often across platforms.

This chapter will focus on the specifics of JSON, which is one of the most widely used techniques for sharing data across apps and platforms.

Identifying Data That Needs to Be Shared

Apps contain data as well as functionality. You may think that a specific app has no data inside it (perhaps a game that users play by entering moves or data), but even that simple case is wrong. Every app contains metadata—its name, category, and description on the App Store as well as a record of related sales data from the App Store. Although that data is managed by the App Store and you as developer, it is still part of the app’s overall data. In addition, there is app-related data that you typically place on your website.

The data that we usually think of as being part of an app is the data that is built into the app itself: the code, storyboards, and app-based documentation and instructions. There is also data that may be stored, such as logs of moves in a game, high and low scores, and other data that is accumulated as the user uses the app. This is the data we normally consider when thinking about sharing data.

There are two types of data sharing for you to think about:
  • Sharing across apps. You may need to share data across apps . A simple example is a photo that you capture using the built-in Camera app on an iPhone. You may then share that with the Photos or Files apps so that you can organize your apps into albums and share them with others. You may export the photo from Photos in another format (perhaps GIF rather than JPEG) to use it in a document or website. And so the shared photo may wend its way through several of your apps (as well as others’ apps, if you send the document to your friends).

  • Sharing across time. When you are playing a game, writing an essay, or creating a movie, you often want to take a break and save it so you can continue working on it another time. That requires you to be able to share the data across time. Remember that when an app is running, its data is stored in memory rather than in persistent storage (like a disk). Memory is a scarce resource, so it needs to be reused when you decide to do something other than work on your game, essay, or movie. The data needs to be copied to some kind of persistent storage so that it can be reloaded when you pick up your game or project later on.

Just to keep you on your toes, a lot of data sharing is of both types: across apps and across time. And as a further consideration, remember that when you share data across apps, you may also be sharing it across devices (from your Camera on your iPhone to Keynote on your Mac and on to your colleague’s Photoshop on a PC).

Considering Security for Sharing Data

As people become more and more aware of the security aspects of data, it is important to consider the security side of sharing it. This is a common trade-off between ease of use for users and protection against allowing bad actors to exploit that ease of use for nefarious purposes.

One point that has become obvious is that trusting to luck is just not a reasonable strategy. Further, assuming that no one would be interested in your data is just as risky. Remember that people tend to reuse identifiers such as passwords so that even if you are sharing what you think is totally innocuous data, you may be sharing a user’s banking PIN or password inadvertently.

Also be aware of the European Union General Data Protection Regulation (GDPR), which took effect on May 25, 2018. It governs data protection and privacy within the EU, but if your app is (or may in the future be) covered by the regulation, you must abide by the regulation.

The Challenges of Sharing Data

The data that your app uses when it is running is stored in memory in whatever format your operating system uses. From the developer’s point of view, the data consists of variables, which are identified as types such as integers or real numbers, as well as the types and classes that you create in your app. When the data is moved to persistent storage (a disk, for example), the data is reformatted. All of this can happen multiple times for any given data within your app as it moves from memory to persistent storage.

From a practical point of view, data cannot maintain its formatting structure as it moves from memory to device and onward. That is why we wind up with various types of data formats depending on the medium and device. To make these reformatting processes work as data is moved back and forth, there are several challenges to be confronted. They are summarized in this section; in the following section, you’ll see how these issues are addressed with JSON (JavaScript Object Notation, but it is used in many languages other than JavaScript) and other modern technologies.

Here are the challenges to be confronted in sharing data:
  • Identifying data elements

  • Managing inconsistent data types

  • Exploring the document and structure issues

Identifying Data Elements

When you talk about sharing data, you have to make it clear what you’re talking about. As noted in this chapter, “data” for an app can take many forms and can reside from time to time in many places, from a computer’s memory to one or more persistent stores. Each has its own formatting rules, but before looking at that, you have to be specific about the data. What is actually shared is often a subset of the app’s data—a log of moves in a game or the goal for a project in a workpaper.

The sharable data elements are often identifiable in the user interface using ordinary non-technical terms, such as paragraph, page, or sentence for words and image for graphics. If you can find a way to translate these UI elements into data that uses standard elements, such as characters of text or the binary string that represents an image, then you can share the data.

In general, the more basic the structure of a sharable format is, the easier it is to share, but there is a trade-off because the code you write to use sharable data that relies on basic structures may be more complex. Fortunately, over time processors become more and more powerful so there is often computing power available to do necessary pre- and post-processing of sharable data.

Managing Inconsistent Data Types

When you get beyond the basics of sharable data, you may encounter inconsistencies in data types . For instance, there is general agreement as to what an integer is (the mathematicians sorted this out centuries ago). However, what an integer is for a specific processor may be different from another processor’s integer. This can let you specify a value of an integer that conceptually exists (for mathematicians) but cannot be stored on a specific operating system or a specific piece of hardware. This is one of the reasons why basic data types are used.

Exploring the Document and Structure Issues

If you look at the samples of JSON code, you’ll see that they are very basic and that they only represent data. They do not provide any formatting, nor do they provide any logical structure of how a document might be presented. There are a number of document-based sharable formats, the most common of which is Extensible Markup Language (XML). It is more powerful when you are dealing with documents, but, as is always the case when the sharable data becomes more complex, it may be more difficult to share it across devices and platforms.

Looking at JSON

In today’s world, JSON is a common way to share data. Its elements are simple and are represented using characters. JSON represents data as objects. A JSON object is delimited by brackets: { and }. Within an object, spaces and return characters don’t matter except for the special case in which they appear within quotes.

Within the { and } delimiters of a JSON object, comma-separated name–value pairs define the elements of the JSON object. The name and value are both enclosed in quotes and are separated by a colon. When the value is a number, it is not quoted.
{
  "name": "Claude Debussy"
}
The value can be an array. In that case, the elements of the array are enclosed in square brackets and are separated by commas, as in the following:
{
  "name": "Claude Debussy",
  "works": ["La Mer", "Pélleas et Mélisande", "Images"]
}
Objects can be nested, as in the following:
{
  "French Composers":  [
    {
    "name": "Claude Debussy",
    "works": ["La Mer", "Pélleas et Mélisande", "Images"]
    },
    {
    "name": "Maurice Ravel",
    "works":["Boléro", "La Valse"]
    }
  ]
}

JSON is readable, particularly in small sections. Because of its simplicity, it has no document-based structure or syntax checking. It is easy to generate from data structures, which is the way much (perhaps all) of the JSON code you will deal with is created. (Chapter 5 will show you how to use the Swift Codable protocol to read and write JSON code.)

Because JSON is so commonly used, you can read it and write it with many common tools. Some JSON code used for a navigation app is shown in Figure 3-1 as it appears when opened in TextEdit. The spacing is whatever has been typed in.
../images/459488_1_En_3_Chapter/459488_1_En_3_Fig1_HTML.jpg
Figure 3-1

JSON in TextEdit

The same JSON file is showed in Figure 3-2 as opened in BBEdit. The text is automatically colored by BBEdit.
../images/459488_1_En_3_Chapter/459488_1_En_3_Fig2_HTML.jpg
Figure 3-2

JSON in BBEdit

In Figure 3-3, you can see the same file opened in Excel. Note that the content is the same, but the spacing within the spreadsheet is done by Excel.
../images/459488_1_En_3_Chapter/459488_1_En_3_Fig3_HTML.jpg
Figure 3-3

JSON in Excel

Finally, in Figure 3-4 you can see the same JSON file opened in Xcode, which applies its own spacing and coloring.
../images/459488_1_En_3_Chapter/459488_1_En_3_Fig4_HTML.jpg
Figure 3-4

JSON in Xcode

Using JSON—The Basics

Despite the different appearance of the same JSON code in the different apps, the structure of the underlying code is the same, and it is easy to take the raw JSON code, which is based only on characters, and transfer it across any communications channel.

If you are creating the JSON code yourself, it’s easy to misplace a quotation mark, comma, bracket, or parenthesis. Because JSON is so straightforward and is so widely available, you can find a multitude of JSON checkers and validators on the web—just use your favorite search engine.

The components of JSON should be familiar to you if you are already familiar with Cocoa or Swift. The comma-separated lists or key–value pairs are the heart of the dictionaries that are used so widely in the operating systems.

Built into Swift you will find code that easily converts dictionaries to JSON and vice versa. The next chapter will give you examples of that code. Furthermore, you’ll see how to use the built-in encoders and decoders (in Swift 4 and later) that perform these operations for you without your needing to write any additional code.

Summary

Sharing data from one app to another, one device to another, or across time barriers is made possible by your using sharable code and standards such as JSON. The power of JSON is derived from its simplicity: it doesn’t encode a document as a whole but rather lets you encode and decode basic structures such as objects (of any kind—not necessarily object-oriented objects), numbers, strings, and arrays. These processes are very fast and easy to use.

The next chapter will explore the built-in tools you use with JSON.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.46.240