Thursday, March 19, 2020

JavaScript JSON


JavaScript JSON Objects


JSON stands for JavaScript Object Notation. JSON is an open standard lightweight format for data interchange. JSON is a format for storing and transporting data consisting of comma-separated attribute-value pairs and array data types. JSON is commonly used to send the information from a server to a web page. JSON is self-describing, human-readable and easy to understand object representation. All the programming languages can be used for reading and generating JSON data.

JSON and JavaScript


The JSON format is syntactically similar to the code for writing JavaScript objects. JavaScript program can be converted to JSON data into native JavaScript objects.

JSON Syntax


  • Data is represented in key-value pairs
  • Data is kept by comma-separated
  • Curly braces are used to hold objects
  • Arrays are represented by Square brackets


JSON Syntax

A key-value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

“color”:” red”

The main difference between the normal JavaScript Object and the JSON Object is that JSON names must be enclosed within double-quotes. We write a JavaScript Object as

employee_obj={eid:117,ename:"Harry",edept:"CSE"};

but a JSON Object is written as

employee_obj={“eid”:117,”ename”:"Harry",”edept”:"CSE"};

JSON Arrays

JSON arrays are created using square brackets and items separated by commas, like in JavaScript:

"cars":[
  {"brand":"Toyota", "Modal":"Innova"},
  {"brand":"Suzuki", "Modal":"Dzire"},
  {"KIA":"Suzuki", "Modal":"Seltos"}
]

 
Converting a JSON Text to a JavaScript Object


We can take a JSON object as a String type to demonstrate the conversion of JSON to JavaScript Object. For example

var car='{"cars":['+
  '{"brand":"Toyota", "Modal":"Innova"},'+
  '{"brand":"Suzuki", "Modal":"Dzire"},'+
  '{"brand":"KIA", "Modal":"Seltos"}]}';

To convert this JSON String into JavaScript Object,  We can use the JavaScript built-in function JSON.parse(),

var car_object = JSON.parse(car);

This object can be used as a normal JavaScript object in a web document.

Example


t<script> 
  var cars='{"car":['+
  '{"brand":"Toyota", "Modal":"Innova"},'+
  '{"brand":"Suzuki", "Modal":"Dzire"},'+
  '{"brand":"KIA", "Modal":"Seltos"}]}';
    var car_js=JSON.parse(cars);
    document.write(car_js.car[0].brand);
</script>

Output:
Toyota