3D Gallery with Great Artwork Imagine Logo with Three Colors Beach Cabin 3D Android Tablet with Different Screens Studio Apartment Red Figured Greek Vase on Blue Background Silver and Gold Flashlight Lake on Fire

JavaScript: JSON

Page 20

JSON

Introduction Syntax Basic JSON. Tap a Button JSON Arrays Summary

Introduction

Learn to create and convert JSON to JavaScript objects, strings and arrays. See interactive examples and JavaScript source code with JSON from ECMAScript 5.

JSON is an acronym for JavaScript Object Notation. It's a data string format. JSON allows developers to transport data between applications, with a simple format.

Syntax

JSON syntax includes name-value pairs, within curly braces. JSON strings require double quotes, whereas JavaScript allows either double or single quotes for strings. JSON name-value pairs are separated by commas.

JSON Arrays

JSON values may include arrays within square brackets. Data within square brackets may include string, number, object, array, boolean or null.

JSON Names

JSON names must be declared with double quotes. JSON names represent JavaScript strings, however unlike JavaScript, JSON names require double quotes. You can't declare JSON names with single quotes.

JSON Values

JSON value types include string, number, object, boolean, array and null. JSON numbers must be integers or floating point values.

Functions, date-time and undefined values aren't allowed with JSON, by default. However JSON values can be converted to functions and date-time.

JSON.parse() converts a JSON string to a JavaScript object.

const dogMultiple = JSON.parse(dogs);

JSON.stringify() converts a JSON string to a JavaScript string.

const dogMultiple = JSON.stringify(dogs);

Basic JSON. Tap a Button

Tap to parse one object.
Tap to stringify one object.
Tap for one dog at a time.
Tap for all dogs in the list.
Tap for a dog attribute.
Tap for a cat attribute.

Button Source Code

The following source code demonstrates how to create and access one JSON attribute-value pair, or an array of JSON attribute-value pairs. The following JavaScript function JSONDogs(n, id) activates each time you tap one of the buttons above.

// Global scope index
// to track each tap of
// the green button.
var idx = 0;

/**
* Display JSON data in an HTML element.
* The first number indicates which
* set of data you want to display.
*
* @param n: The switch statement's number.
* @param id: An HTML element ID
*/
function JSONDogs(n, id){

let element = document.getElementById(id);
element.innerHTML = '';

// dog is just a name value pair.
let dog = '{"Dog":"Smart"}';

// cat is just a name value pair.
let cat = '{"Cat":"Smarter"}';

// dogs contains one name-value pair.
// the value is an array of name-value pairs.
// The end result in JavaScript
// is one long string.
// Each line is appended with the + operator.
let dogs ='{ "Dogs" :  [' +
'{ "Breed":"Doberman"}, ' +
'{ "Breed":"Labrador"}, ' +
'{ "Breed":"Pit Bull"} ]}'; 

// JSON.parse converts
// a JSON string to a 
// JavaScript object.
const dogMultiple = JSON.parse(dogs); 

switch (n){
case 0:

if (idx == dogMultiple.Dogs.length){
idx = 0;
}

element.innerHTML = dogMultiple.Dogs[idx].Breed;
idx++;
break;

case 1:

// Iterate over the Dogs array of objects.
// Display the value for each breed:
for (let i = 0; i < dogMultiple.Dogs.length; i++){
element.innerHTML += dogMultiple.Dogs[i].Breed;
element.innerHTML += '<br>';
}

break;

case 2:

const dogType = JSON.parse(dog);
element.innerHTML = "A Dog is "+dogType.Dog;
break;

case 3:

const catType = JSON.parse(cat);
element.innerHTML = "A Cat is "+catType.Cat;
break;

case 4:

const dogparse = JSON.parse(dog);
element.innerHTML = "JSON.parse(dog):<br>" +dogparse;
break;

case 5:

const dogstring = JSON.stringify(dog);
element.innerHTML = "JSON.stringify(dog):<br>" +dogstring;
break;

default:

if (element != null){
element.innerHTML = "The selection was invalid.";
}
break;

}
}

JSON Arrays

A simple array in JSON format displays below.

let jaAnimals = '["Hyena", "Frog", "Butterfly"]';

Convert the JSON array to a JavaScript array.

let jsaAnimals = JSON.parse(jaAnimals);

a JSON string with properties where one attribute is an array, displays below.

let jAmphibians= '{"type":"Amphibian",'+
' "region":"North America",'+
' "species":'+
'["Frogs","Toads","Salamaders","Newts"]}';

Convert JSON to a JavaScript object with attribute value pairs. One value is an array.

let jsAmphibians = JSON.parse(jAmphibians);

JSON Arrays. Tap a Button

Tap for basic array.
Tap for object with array.

JSON Arrays. Source Code

The following JavaScript creates a simple JSON array, converts that array to JavaScript, then displays the array.

The code creates a more complex JSON object with attribute-value pairs. The last value is an array. Code displays each value plus the elements in the array.

/**
* Display JSON data in an HTML element.
* The first number indicates which
* set of data you want to display.
*
* @param n: The switch statement's number.
* @param id: An HTML element ID
*/
function JSONArrays(n,id){
	
let element = document.getElementById(id);
element.innerHTML = "";
// JSON Array
let jaAnimals = '["Hyena", "Frog", "Butterfly"]';
// Convert to JavaScript Array:
let jsaAnimals = JSON.parse(jaAnimals);

// JSON Object 
// with Array
let jAmphibians= '{"type":"Amphibian",'+
' "region":"North America",'+
' "species":'+
'["Frogs","Toads","Salamanders","Newts"]}';

// Convert to JavaScript
// object with Array.
let jsAmphibians = JSON.parse(jAmphibians);

switch(n){
case 0:

// Iterate over array:
for(let i = 0; i < jsaAnimals.length; i++){
element.innerHTML += jsaAnimals[i];
element.innerHTML +="<br>";
}
break;

case 1:

element.innerHTML = "Animal type: "+jsAmphibians.type;
element.innerHTML += "<br>";

element.innerHTML += "Animal region: "+jsAmphibians.region;
element.innerHTML += "<br>";

element.innerHTML += "<br>List of Amphibians:<br>";

// Display the internal array:
for(let i = 0; i < jsAmphibians.species.length; i++){
element.innerHTML += jsAmphibians.species[i];
element.innerHTML +="<br>";
}
break;
	
default:	
if(element != null){
element.innerHTML = "The selection was invalid.";	
}
}
	
}

Summary

You learned to create and convert JSON to JavaScript objects, strings and arrays. You saw interactive examples and JavaScript source code with JSON from ECMAScript 5.

See the source code for this page, json-examples.js. The code on this page includes comments for clarity. The JavaScript itself minimizes comments for faster download time.

Learn to create a simple client-server with JavaScript, PHP and JSON, on the next page.

Learn JavaScript

JavaScript's the foundation of Web developer and Website design skills. This free and unique JavaScript tutorial includes some new or seldom used, but useful features.

Tags
canvas drawing, web design, web designing course, how to become a web developer, coding websites, website developers,learning web design, html web design, html5 canvas tutorials, coding Website, html5 canvas, learn to code, html5 canvas tutorial,learn html tutorial, simple html tutorial

Ads >
Create 3D Games: Learn WebGL Book 2 Simple Shaders: Learn WebGL Book 4
3D Programming for Beginners: Learn WebGL Book 1

for Web graphics!

Copyright © 2022 Amy Butler. All Rights Reserved.