JSON and JavaScript

JavaScript Object Notation (JSON) 

JavaScript Object Notation (JSON) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

Here is an example of JSON data:

{

   “name”: “Laurence Svekis”,

   “age”: 41,

   “address”: {

       “street”: “10 Main St”,

       “city”: “New York”,

       “state”: “NY”,

       “zip”: 10001

   },

   “phoneNumbers”: [

       {

           “type”: “home”,

           “number”: “212 123-1234”

       },

       {

           “type”: “work”,

           “number”: “646 123-4567”

       }

   ]

}

JavaScript provides methods JSON.stringify() and JSON.parse() to convert between JSON and JavaScript objects.

Example of converting JavaScript object to JSON:

Code Example : 

const object = { name: ‘John Doe’, age: 35 };

const json = JSON.stringify(object);

console.log(json);

Example of converting JSON to JavaScript object:

Code Example : 

const json = ‘{“name”:”John Doe”,”age”:35}’;

const object = JSON.parse(json);

console.log(object.name); // “John Doe”

In summary, JSON is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is based on a subset of JavaScript and can be used with many programming languages. JavaScript provides built-in methods for converting between JSON and JavaScript objects.

There are several ways to get JSON data with JavaScript. One common method is to use the fetch() function to make an HTTP request to a server that returns JSON data. The fetch() function returns a promise that resolves to a response object, from which the JSON data can be extracted using the json() method.

Here is an example of how to get JSON data from a remote server:

fetch(‘https://api.example.com/data’)

  .then(response => response.json())

  .then(data => {

    console.log(data);

  })

  .catch(error => {

    console.error(‘Error:’, error);

  });

Another way to get JSON data is to load it from a local file using the XMLHttpRequest object or the fetch() function.

Here is an example of how to get JSON data from a local file:

var xhr = new XMLHttpRequest();

xhr.open(‘GET’, ‘data.json’, true);

xhr.responseType = ‘json’;

xhr.onload = function() {

  if (xhr.status === 200) {

    console.log(xhr.response);

  }

};

xhr.send();

In summary, there are several ways to get JSON data with JavaScript, including using the fetch() function to make an HTTP request to a server that returns JSON data or by loading JSON data from a local file using the XMLHttpRequest object or the fetch() function. Once you have the data you can use json() to access the data.

const url = ‘my1.json’;

const output = document.querySelector(‘.output’);

const dataSt = ‘{“name”:”Laurence Svekis”,”age”:41,”address”:{“street”:”10 Main St”,”city”:”New York”,”state”:”NY”,”zip”:10001},”phoneNumbers”:[{“type”:”home”,”number”:”212 123-1234″},{“type”:”work”,”number”:”646 123-4567″},{“type”:”work 2″,”number”:”343 133-4567″}]}’;

console.log(dataSt);

const dataObj = JSON.parse(dataSt);

console.log(dataObj);

output.addEventListener(‘click’,getJsonData);

function getJsonData(){

output.textContent = ‘loading…..’;

fetch(url)

.then(response => response.json())

.then(data => {

myOutput(data);

})

.catch(error => {

console.error(‘Error:’,error);

})

}

function myOutput(data){

let html = `<h1>${data.name}</h1>

<div>${data.address.street}</div>

<div>${data.address.city}</div>

<div>${data.address.state}</div>

<div>${data.address.zip}</div>

`;

data.phoneNumbers.forEach(el =>{

html += `<small>${el.type} – (${el.number})</small><br>`;

})

html += JSON.stringify(data);

output.innerHTML = html;

}

const url = ‘my1.json’;

const output = document.querySelector(‘.output’);

const dataSt = ‘{“name”:”Laurence Svekis”,”age”:41,”address”:{“street”:”10 Main St”,”city”:”New York”,”state”:”NY”,”zip”:10001},”phoneNumbers”:[{“type”:”home”,”number”:”212 123-1234″},{“type”:”work”,”number”:”646 123-4567″},{“type”:”work 2″,”number”:”343 133-4567″}]}’;

console.log(dataSt);

const dataObj = JSON.parse(dataSt);

console.log(dataObj);

output.addEventListener(‘click’,getJsonData);

function getJsonData(){

output.textContent = ‘loading…..’;

fetch(url)

.then(response => response.json())

.then(data => {

myOutput(data);

})

.catch(error => {

console.error(‘Error:’,error);

})

}

function myOutput(data){

let html = `<h1>${data.name}</h1>

<div>${data.address.street}</div>

<div>${data.address.city}</div>

<div>${data.address.state}</div>

<div>${data.address.zip}</div>

`;

data.phoneNumbers.forEach(el =>{

html += `<small>${el.type} – (${el.number})</small><br>`;

})

html += JSON.stringify(data);

output.innerHTML = html;

}

{

“name”: “Laurence Svekis”,

“age”: 41,

“address”: {

“street”: “10 Main St”,

“city”: “New York”,

“state”: “NY”,

“zip”: 10001

},

“phoneNumbers”: [

{

“type”: “home”,

“number”: “212 123-1234”

},

{

“type”: “work”,

“number”: “646 123-4567”

},

{

“type”: “work 2”,

“number”: “343 133-4567”

}

]

}

<!DOCTYPE html>

<html>

<head>

<title>Learn JavaScript</title>

</head>

<body>

<h1>Complete JavaScript Course </h1>

<div class=”output”>Data</div>

<script src=”app7.js”></script>

</body>

</html>