官术网_书友最值得收藏!

The Hello World program with JSON

Now that we have a basic understanding of JSON, let us work on our Hello World program. This is shown in the screenshot that follows:

The preceding program will alert World onto the screen when it is invoked from a browser. Let us pay close attention to the script between the <script> tags.

In the first step, we are creating a JavaScript variable and initializing the variable with a JavaScript object. Similar to how we retrieve data from a JavaScript object, we use the key-value pair to retrieve the value. Simply put, JSON is a collection of key and value pairs, where every key is a reference to the memory location where the value is stored on the computer. Now let us take a step back and analyze why we need JSON, if all we are doing is assigning JavaScript objects that are readily available. The answer is, JSON is a different format altogether, unlike JavaScript, which is a language.

Note

JSON keys and values have to be enclosed in double quotes, if either are enclosed in single quotes, we will receive an error.

Now, let us take a quick look at the similarities and differences between JSON and a normal JavaScript object. If we were to create a similar JavaScript object like our hello_world JSON variable from the earlier example, it would look like the JavaScript object that follows:

The big difference here is that the key is not wrapped in double quotes. Since a JSON key is a string, we can use any valid string for a key. We can use spaces, special characters, and hyphens in our keys, which is not valid in a normal JavaScript object.

When we use special characters, hyphens, or spaces in our keys, we have to be careful while accessing them.

The reason the preceding JavaScript statement doesn't work is that JavaScript doesn't accept keys with special characters, hyphens, or strings. So we have to retrieve the data using a method where we will handle the JSON object as an associative array with a string key. This is shown in the screenshot that follows:

Another difference between the two is that a JavaScript object can carry functions within, while a JSON object cannot carry any functions. The example that follows has the property getName, which has a function that alerts the name John Doe when it is invoked:

Finally, the biggest difference is that a JavaScript object was never intended to be a data interchange format, while the sole purpose of JSON was to use it as a data interchange format.

主站蜘蛛池模板: 商洛市| 高阳县| 平阴县| 铁岭市| 自贡市| 边坝县| 潞城市| 和顺县| 肃宁县| 东兴市| 新宁县| 彭山县| 建瓯市| 大田县| 泰来县| 徐州市| 宁城县| 广西| 徐州市| 漾濞| 子长县| 曲靖市| 钦州市| 鹰潭市| 布尔津县| 泽普县| 昭平县| 贵德县| 楚雄市| 绥滨县| 射洪县| 密山市| 古蔺县| 盘山县| 星子县| 宝鸡市| 新竹县| 阳城县| 蚌埠市| 东阿县| 尼玛县|