- Real-Time 3D Graphics with WebGL 2
- Farhad Ghayour Diego Cantor
- 345字
- 2021-06-10 19:43:00
Time for Action: Encoding and Decoding JSON
Most modern web browsers support native JSON encoding and decoding. Let's examine the methods available inside this object:
Let's learn how to encode and decode with the JSON notation by creating a simple model—a 3D line. Here, we will be focusing on how we do JSON encoding and decoding. Follow the given steps:
- In your browser, open the interactive JavaScript console. Use the following table for assistance:
- Create a JSON object by typing the following:
const model = { vertices: [0, 0, 0, 1, 1, 1], indices: [0, 1] };
- Verify that the model is an object by writing the following:
typeof(model); // outputs "object"
JavaScript Type-Checking
Since many things in JavaScript are objects, it is recommended that you are more rigorous with type-checking. We will just use typeof for demonstration purposes. Additionally, there are many utility libraries, such as Lodash ( https://lodash.com), that extend JavaScript features to provide these operations and more.
Since many things in JavaScript are objects, it is recommended that you are more rigorous with type-checking. We will just use typeof for demonstration purposes. Additionally, there are many utility libraries, such as Lodash ( https://lodash.com), that extend JavaScript features to provide these operations and more.
- Let's print the model attributes. Write this in the console (press Enter at the end of each line):
model.vertices // outputs the vertices
model.indices // outputs the indices
- Let's create a JSON text:
const text = JSON.stringify(model);
alert(text);
- What happens when you type text.vertices?
- As you can see, you get a message saying that text.vertices is undefined. This happens because text is not a JavaScript object, but a string with the peculiarity of being written according to JSON notation to describe an object. Everything in it is text, and so it does not have any fields.
- Let's convert the JSON text back into an object. Type the following:
const model2 = JSON.parse(text);
typeof(model2); // outputs "object"
model2.vertices; // outputs vertices
What just happened?
We have learned to encode and decode JSON objects. These exercises are relevant because we will use the same process to define our geometry to be loaded from external files. In the next section, we will see how to download geometric models specified with JSON from a web server.