Getting started with JSON in JavaScript

JSON is an acronym of JavaScript Object Notation. It is a storage format derived from JavaScript programming language and it is language independent.It is a text-based data format that is used to store and transfer data. It’s quite important to know while data which we fetch from external API are always in JSON format.

  • It can transport the data from server to client, client to server and server to server.
  • It can generate and store data from user input.
  • It can also build and verify data

JSON Syntax:

JSON objects are in a .json file which is quite similar to object literal syntax which consists of name, value pairs but the format is text only. Both the name and values are quoted in double quotation.

Points to remember:

  • Data is in name/value pair.
  • Curly braces hold objects.
  • Square brackets hold arrays.
  • Data is separated by commas.

If JSON objects are in .js or .html file then the syntax is

In terms of Syntax JSON is similar to JavaScript objects but the name in JavaScript objects are not in double quotes.

JSON Data:

JSON data is written as name and a value pairs. A name/value pair is like field name in double quotes followed by colon (:), then value.

JSON Objects:

As mentioned earlier JSON objects are in curly braces.

JSON Arrays:

JSON arrays are in square brackets.

Here ‘names’ is an array, and it contains 3 objects. Each object is a record of a person.

Accessing JSON Data:

JSON data can be accessed using dot (.) notation.

Output:
Anna
Mills

We can also use square brackets to access JSON data.

JSON vs JavaScript Objects:

JSONJavaScript Objects
The name in name/value pair should be in double quotesThe name can be without double quotes
JSON cannot contain functionsJavaScript objects can contain functions
JSON can be created and used by other programming languagesJavaScript objects can only be used in JavaScript.

Converting JSON to JavaScript Object:

You can convert JSON data to JavaScript object using in-built JSON.parse() function.

Output:

Converting JavaScript object to JSON:

You can convert JavaScript object to JSON using in-built JSON.stringify().

Output:

Keypoints to note:

  • JSON syntax is like Object literal where both name-value pair is in inverted commas.
  • JSON.stringify() Object to JSON
  • JSON.parse() JSON to Object

Difference between var, let and const in Javascript

The var, let and const are the keywords basically used in Javascript to declare variables. Among them var is the oldest way of declaring a variable. Other two let and const are introduced in ES2015 (ES6) update. Nowadays let and const are used more frequently in modern javascript compared to var.

In this article, we will try to understand the difference between them in respect to their scope.

Before getting into the difference first we need to know what is function scope and block scope.

Function Scope – Created by declaring a function

Block Scope – Created by if statement, for loops, while loops etc.

var in Javascript:

Var declarations are globally or functionally scoped. The var is globally scoped when it is declared outside a function and it is available for the whole program. Var is functionally scoped when it is declared inside a function.

Example of var with global scope:

Output:

2

2

The scope of variable a is global and it can be accessed anywhere in the program.

Example of var with function scope:

Output:

2

Reference Error: a is not defined

The scope of variable is within the function so if we try to access outside the function it shows error.

Limitation with var:

Var variable can be redeclared and updated. If we accidentally declared a new variable with the same name, it will override the existing value of that variable.

Output:

7

Last assigned value 7 is updated to the variable a.

If we use the var variable before declaration it is initialized with undefined value.

Output:

Undefined.

Let in javascript:

It is an improved version of var keyword. Let does not allow variable redeclaration.

Output:

Syntax error: Identifier ‘a’ has already been declared.

Scope of let:

Let is block scoped.

Output:

20

10

Now try to access b outside the function.

Output:

Reference Error : b is not defined.

If we use a variable before declaration it is not initialized with undefined just returns an error.

Output:

Reference Error: Cannot access ‘a’ before initialization

const in javascript:

Const variables maintain constant values. They share some similarities with let.

Like let declarations, const are block scoped. The difference is that unlike let, const cannot be updated or re-declared.

Output:

Type Error: Assignment to constant variable

User cannot change the properties of const object but they can change the value of properties of const object.

Output:

Type Error : Assignment to const variable.

Points to remember

varletconst
Function scopedBlock scopedBlock scoped
Allow duplicate identifiersDoes not allow duplicate identifiersDoes not allow duplicate identifiers
Value can be updatedValue can be updatedValue cannot be updated
Hoisted and initialized with undefinedHoisted but error if we try to access before declarationHoisted but error if we try to access before declaration

How to dynamically create a sap.m.table in SAP UI5

Required steps:

  1. define and initialize a variable with JSON Data ( Key value pairs )
  2. define a JSON Model reference variable and transfer the JSON Data through the constructor
  3. define a sap.m.Table reference and set the column Headings. Use the placeAt method to set the content
  4. Set the JSON Model to the table
  5. Assign the cell values to each row using the columnListItem class. Finally call the bindAggregation method of the Table reference and pass the cell values in the method call.

CODE EXAMPLE

SAP M TABLE

        <script type='text/javascript'>

var jsonData = [ {columnOne : “Data row A1”, columnTwo : “Data row 100”, columnThree : “Data row hundred”},

             {columnOne : "Data row A2", columnTwo : "Data row 200", columnThree : "Data row two hundred"},

             {columnOne : "Data row A3", columnTwo : "Data row 300", columnThree : "Data row three hundred"}  ];

var jsonModel = new sap.ui.model.json.JSONModel(jsonData);

var mTable = new sap.m.Table({

            columns : [

                  new sap.m.Column({ header  :  new sap.m.Label({  text : "Column One" }) }),

                  new sap.m.Column({ header  :  new sap.m.Label({  text : "Column Two" }) }),

                  new sap.m.Column({ header  :  new sap.m.Label({  text :  "Column Three" }) })

]

}).placeAt(“content”);

mTable.setModel(jsonModel);

mTable.bindAggregation(“items”, {

path : “/”,

template : new sap.m.ColumnListItem({

cells : [

new sap.m.Text({ text : “{columnOne}” }),

new sap.m.Text({ text : “{columnTwo}” }),

new sap.m.Text({ text : “{columnThree}” }),

]

})

});