JSON / Object Tutorial

Working with JSON data is a common Thunkable Discussion topic. Here I will try to answer the most common questions and provide solutions to the most common problems.

This tutiorial has six parts:

  1. Basic JSON
  2. JSON Errors
  3. Intermediate JSON
  4. Advanced JSON
  5. Firebase Realtime DB and Cloud Variables
  6. Web API

The companion project with all examples can be found here.

8 Likes

Part 1 Basic JSON

Key Ideas

  1. JavaScript Object Notation (JSON) is a standard cross platform text format for sharing data
  2. JSON is text composed of name-value pairs in the format {name:value}
  3. Thunkable blocks allow for the creation, modification, coding, and decoding of JSON data

What is JSON?
JavaScript Object Notation (JSON) is a standard cross platform text format for sharing data. Since Thunkable is built on Blockly (which started as a graphic JavaScript code generator) it make sense to incorporate the JavaScript native JSON features to store and share data.

Seriously, what is JSON?
JSON is text. As the acronym suggestions, it is text which represents an object. And what is an object? A JSON object (which is different from an OOP object), is a collection of name-value pairs.

Come on @drted, what is a name-value pair?
Name-value pairs are just that. The name of a characteristics and the value of that characteristics. For instance, my Thunkable alias is drted. So the NAME is alias and the VALUE is drted. In JSON this would be represented as:

{"alias":"drted"}

A few things to notice:

  1. The object starts and ends with braces { }
  2. The name is enclosed by double quotes " "
  3. The value is enclosed by double quotes " "
  4. The name and value are separated by a colon :
  5. Capitalization matters! Alias is not the same as alias

In later lessons, we will extend this format to more complex data structures. But it is CRITICAL to understand that JSON is fundamentally a text string composed of name value pairs.

Thunkable Object Blocks
But this is Thunkable, therefore we are going to use blocks, not code. So let’s create an app level variable with the object {"alias":"drted"} using the Create Object block
image

Next, let’s create a screen to allow the user to set the value of the alias and display the value in a label using the get property block
image
The output is:
image

Alternatively, the Set Property block could be used to change the alias property of an existing object:
image
image

Decoding and encoding JSON with Thunkable Blocks
The real power of JSON is communicating between applications. For Thunkable to communicate with other appliations, the object blocks need to be converted into JSON, and JSON will need to be converted into objects. To convert objects to JSON, use the generate JSON from object block:


image

To convert JSON into a Thunkable Object we can use the get object from JSON block:


image

As you probably already notice, it can get a little confusing remembering if a variable is text representing JSON or an object. Confusing these two forms and how to detect mistakes is the topic of the next section.

Special Case: Numbers
At the beginning of the lesson, I indicated that the value is encoled by double quotes " ". This is true when the value is a string (red Text block). If the value is stored as number (blue math block), no quotes are used:


image

Additional Reading

6 Likes

Part 2 JSON Errors

Un-Thunkable
In a perfect world, everyone would have everything they need for an abundant life. Guess what, we don’t live in a perfect world. :poop: happens. When it does, Thunkable misbehaves :skull_and_crossbones:. But these misbehaviors are predictable. This section will cover the most common errors and misbehaviors when working with JSON in Thunkable. When you understand the fundamentals of JSON and how Thunkable misbehaves, you will be able to identify 90% of all JSON-related errors immediately.

null Object
null is a little tricky to describe. It is not the word “null”. It is not a blank or empty value. It is simply nothingness!

Thunkable does NOT like null. Thunkable will crash. If we create a variable, set it to null, then try to treat it as an object, the thunkable app will crash.

When using the Web Live Test, the screen simply goes blank (white). When using the android live test, you will receive a message:

Likewise, trying to set a property of a null will cause Thunkable to crash:

The simpliest way to fix this problem is to first check to make sure the object is not null.


And don’t worry about this affecting the end user experience. If you app is working correctly, they will never see this message. :thinking:

null Value
What if an object has been defined, the name has been defined, but the value is null?


This is where things get a little wierd. If the value is set to null and you display it in a label, it will show null. That looks like the value is “null”.

But let’s take a closer look by asking thunkable to generate the JSON from the object


Notice anything strange? alias is surrounded by quotes, but null is not. Remember that JSON values containing strings are enclosed by quotation marks?

Once again, null is not the letters n-u-l-l, but a special case. Hence, it is stored in JSON as if it were a number. Weird, but true. :confounded:

Here is a straightforward illustration of the point that a null value without quotes is not a word, but a special value.


image

The key lesson here is that even if the label shows the word null, you need to check for the special value of null (found in the logic blocks).

Text is not JSON
Working with external services (Web APIs, data sources, web viewers, etc.) often share date using JSON. As discussed previously, the get object from JSON block can convert text to a Thunkable object. But what if the JSON is not propertly formatted?

In the example below, the text is missing the final }


Thunkable simply crashes when this is attempted. Web Apps just go blank, device Live Test have an error message we have seen before.
image

To keep the app from crashing, there are a few simple checks you can make:

  1. Trim off leading and trailing spaces
  2. Check that the first character is a { and the last character is a }
  3. If the string checks out, use it.
  4. If the string doesn’t check out, show a warning message

Variable not object
Despite our best efforts, occasionally a variable is set to an unexpected value. This can often occur when you accidentally set the variable to the JSON string, not a JSON object.


This will return the result undefined.

If you were paying attention to the null discussion, you might expect undefined to be something other than the string undefined. Well you would be right. Unfortunately undefined is not a string and there is no special block called undefined. But all hope is not lost! You can create a check that Thunkable will recognize by comparing the expected value to a known undefined value.


The good new is that you don’t actually need to do this. This type of error usually only occurs during development. As soon as you display the variable and see undefined, you now know what one of the sources is. Another source is described below.

Property does not exist
Similarly, if the variable is an object, but the property doesn’t exist, you will also get a result of undefined.

Strategies to prevent this from occuring are discussed in the Intermediate JSON and Advanced JSON discussions below.

[object Object]
Just as Thunkers sometimes treat JSON text as a Thunkable objects, if you are anything like me, you will eventually treat an object like text. Luckily, setting a label to an object creates a very distinctive message.

image

Summary
If you survived this TL;DR post, you now can troubleshoot the following errors when working with JSON:

  1. Thunkable crashes
  2. Thunkable displays undefined
  3. Thunkable displays [object Object]
  4. Thunkable displays null

Congratulations!, looking for the 4 situations will resolve 19 out of 20 JSON related problems. the remaining issues will be addressed in the sections below.

4 Likes

Part 3 Intermediate JSON
Under construction

  1. Objects with multiple properties
  2. Nested Objects
  3. Arrays/Lists

Now that you understand Basic JSON and JSON Errors we can now expand into more complex JSON topics.

Objects with multiple properties
In it’s simpliest form, JSON is made of name:value pairs. But the power of JSON resides in the create of objects with mulitple properties. Let’s expand the example of {"alias":"drted"} to include mulitple properties.


Now the JSON is starting to look like a real application (a user profile).

Displaying any property follows the same pattern used in JSON basics


image

Nested Objects
Now we are ready to talk about how objects are REALLY used! Object can be nested inside of other objects.For this example I will create a sub object containing various ways to contact the user

There are mulitple way to navigate nested JSON objects. The Advanced JSON Tutorial will cover how to navigate complex unknown nested JSON objects. For now, let’s look a 2 basic techniques.

Although it takes a few extra blocks the most straightfoward way to navigate nested objects is to set a variable for each level of the hierarchy.

The first block sets Level 1 to the value in the contacts property. Since the contacts property is another object, I can once again use the get property...of object block to retrieve the value of the email property. Now I can simply set the label to the value in Level 2.

An alternative technique involves using nested get property ... of object blocks. Start with the property of the deepest nested property. In this case, the email property in level 2 of the object.

Then, instead of supplying the object directly, I access the contact property of the Nested Object variable

Once you understand this technique, it is a fast and easy solution requiring very few blocks. For reasons we will discuss later, I would recommend against this technique.

How are nested objects translated into JSON text?

{
“alias”:“drted”,
“status”:“Power Thunker”,
“location”:“Corvallis, Oregon, USA”,
“contacts”:{“email":"drtedwilliams@gmail.com”,“mobile”:“1-503-555-5555”,“twitter”:“@drdrinkie”}
}

Notice the contacts property contains another set of braces. This is an important clue when working with external JSON sources: Mulitple sets of braces mean nested objects.

JSON Arrays (aka Thunkable Lists)
We have now seen how objects, bound by sets of braces {}, can be nested one inside another. But there is another way to nest objects within a JSON string, Arrays. Thunkable refers to JSON Arrays as lists. I will use those terms interchangeably.

List are bound by brackets [] and elements in a list are separated by commas, much like properties of a JSON object. You may find it helpful to think of a JSON array as if it were a JSON object without the names. For instance here are 2 examples of JSON text:
JSON Object: {"alias":"drted" ,"status":"Power Thunker","location":"Corvallis"}
JSON Array: ["drted", "Power Thunker", "Corvallis"]

And their Thunkable Blocks

Although Thunkable blocks separate OBJECT (pink) blocks from LIST (baby blue) bocks, the JSON DNA of the Thunkable list is revealed in the ability to use the generate JSON from object block on a Thunkable list object:
image

For more information on JSON Arrays, check out this article 5. Arrays, Objects, Functions and JSON - Mixu's Node book.

In the example above, the list contained text (aka strings), but lists can include anything, including objects:



Notice that since it is a LIST of OBJECTS, the braces [] are the first and last characters, while the brackets {} are inside the braces.

Similarly, an object can contain a list:


Notice in this example, because the OBJECT is the top level element and the list is a PROPERTY of the object, the brackets {} are the top level and the braces are inside the property friends

If you survived this TL;DR post, you can now:

  1. Create objects with multiple properties
  2. Create and identify objects within objects
  3. Create and identify list of objects and objects with lists

That is a heck of a lot of technical content. Try building a few apps using what you have learned before you move on to the next lesson, where we will explore how to programatically navigate JSON hierarchies.

5 Likes

Part 4 Advanced JSON
coming soon

2 Likes

Part 5 Firebase Realtime DB and Cloud Variables
coming soon

2 Likes

Part Web API
coming soon

2 Likes

This is great @drted! Very useful to beginners with JSON like me.

3 Likes

Oh wow! Hugely useful. And very timely since my students are diving into APIs and JSON for the first time. Thank you for making this!

3 Likes

Excellent tutorial. PLEASE keep them coming.

Yes, please do continue these awesome tutorials!

Sorry for the lag @jeffd, @codeswept, @tatiang. I’ve had a couple of other projects demanding my attention (work, continuing education, etc.)

2 Likes

When is the web api tutorial coming out?

Working on it… :wink:

Me first! :wink:

3 Likes

I really need this :c

Drted, Great tutorial. Thank you. Please send more!