Working With Json in Javascript

by admin Date: 11-02-2019 javascript JSON jQuery


JSON is short for JavaScript Object Notation and an easy - to - access way to store information. In short, it gives us a collection of human - readable data that we can access in a very logical way.

In addition to RSS feeds, any sites now share data using JSON, and for good reason.

JSON feeds can be loaded asynchronously much more easily than XML / RSS.

Although it’s derived from JavaScript it may be used with many programming languages. In this article however, we’ll be focusing on the use of JSON in JavaScript.

How do we use JSON in a project?

As described above, a JSON is a string whose format very much resembles JavaScript object literal format.

You can include the same basic data types inside JSON as you can in a standard JavaScript object — strings, numbers, arrays, booleans, and other object literals.

Where do we use JSON?

  • Data storage
  • Data configuration and verification
  • Generating data structures from user input
  • Data transfer from client to server, server to client, and between servers

JSON is also used with AJAX, asynchronous JavaScript and XML. AJAX is often used to transfer data without refreshing the browser page. Later in this article, we'll see how to make an AJAX request for a JSON file and show the content in the browser.

JSON Syntax & Structure

JSON syntax is derived from JavaScript object notation syntax:

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

JSON data is written as name/value pairs.

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

{ "key": "value" }
{ "name": "Pluto" }
JSON names require double quotes. JavaScript names don't.

Data Types

The following data types can be used with JSON:

  • strings (in double quotes)
  • numbers
  • objects (JSON object)
  • arrays
  • Booleans (true or false)
  • null

In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:

  • a function
  • a date
  • undefined

In JSON, string values must be written with double quotes:

 

Use cases

As a simple example, information about me might be written in JSON as follows:

{ 
  "name":"Paul", 
  "age":30, 
  "address":{
        "street":"1 Main St",
        "city": "London"
  },
  "interests":["design", "sports"]
}

Here we have a name set as a string, age as a number, the address is an embedded object and the interests are an array of strings.

If you work with JSON, you may also find JSON as an object or string in a program context. If your JSON object is in a file.js or.html, the variable will probably be set. Our example would then look like:

let contacts = 
{ 
  name:"Paul", 
  age:30, 
  address:{
        street:"1 Main St",
        city: "London"
  },
  interests:["design", "design"]
}

Or if stored as a string, it's going to be a single line::

let contacts = { 
	"name":"Paul", 
	"age":30, 
	"address":{ 
			"street":"1 Main St", 
			"city": "London"
	}, 
	"interests":["deesign", "design"]}
    

Naturally writing on multiple lines in the JSON format makes it much more readable, especially when dealing with a lot of data. JSON ignores the whitespace between its elements, so you can space your key - value pairs to facilitate the eye data!

JSON & JavaScript

Let's do an example. Create an HTML file as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JSON Demo</title>
</head>
<body>
  <script> 
    let contacts = {
      name: "Paul",
      age: 30,
      address: {
        street: "1 Main St",
        city: "London"
      },
      interests: ["design", "cooking"]
    }
  </script>
</body>
</html>

We can access our JSON data through the console using dot notation, like so:

contacts.name            // Paul
contacts.age             // 30
contacts.address.street  // 1 Main St
contacts.address.city    // London
contacts.interests[0]    // design
contacts.interests[1]    // cooking

While developing a JavaScript application, you will sometimes want to serialize your data into a plain string. This can be useful for things like:

  • Storing object data in a database
  • Outputting object data to the console for debugging
  • Sending object data over AJAX or to an API

The simple syntax for converting an object to a string is:

JSON.stringify()

Let’s return our previous example and pass our contacts object into the function.

let contacts = {
  name: "Paul",
  age: 30,
  address: {
    street: "1 Main St",
    city: "London"
  },
  interests: ["design", "cooking"]
}
let s = JSON.stringify(contacts);

We’ll see in the console, the JSON available as a string rather than an object.

{"name":"Paul","age":30,"address":{"street":"1 Main St","city":"London"},"interests":["design","cooking"]}

To do the opposite, we use the JSON.parse() function.

JSON.parse()

To convert a string back into a function we use JSON.parse() function.

let s = JSON.parse(contacts);

Make sure the text is written in JSON format, or else you will get a syntax error.

Looping through arrays

When working with JSON, it is often necessary to loop through object arrays. Let's create a fast array:

let users = [
  {
    name: "Paul",
    age: 30
  },
  {
    name: "Sylvia",
    age: 38
  },
  {
    name: "Luis",
    age: 45
  }
];

And now, letscreate a for loop, to iterate through our data:

for (var i = 0; i < users.length; i++) {
	console.log(users.name);
}
------------
output:
Paul
Sylvia
Luis

Lets see revise our HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JSON Demo</title>
</head>
<body>
  <ul id="users"></ul>
  <script>
    let contacts = {
      name: "Paul",
      age: 30,
      address: {
        street: "1 Main St",
        city: "London" 
      },
      interests: ["design", "cooking"]
    }
    
// let s = JSON.stringify(contacts);
// let s = JSON.parse(contacts);

    let users = [
      {
        name: "Paul",
        age: 30
      },
      { 
        name: "Sylvia",
        age: 38 
      },
      {
        name: "Luis",
        age: 45
      }
    ];
   
	let output = '';
    for (
		var i = 0; i < users.length; i++) {
      
		// console.log(users.name); 
      	output += '<li>'+users.name+'</li>';
    }
    document.getElementById('users').innerHTML = output;
  </script>
</body>
</html>

How to access JSON from a URL

We'll need to access JSON most of the time from a URL.

There is an additional step involved in this, we will use AJAX to make a GET application for the file.

Take the above JSON string for our demo and put it in a new file called users.json. It should be like:

[
  {
    
"name": "Paul",
    
"age": 30
  },
  { 
    
"name": "Sylvia",
    
"age": 38
  }, 
  { 
    
"name": "Luis",
    
"age": 45
  }
]

 

Now we’ll make an XMLHttpRequest().

let request = new XMLHttpRequest();

We'll open the file users.json via GET (URL) request.

request.open('GET', 'users.json', true);

Clearly, if your JSON file is stored externally, you'd replace users.json with the full URL address, e.g. https / api.myjson.com/demo/sample.json .

Now we parse our JSON data within the onload function. And then loop through the data, displaying in our ul element..

request.onload = function () {
  // Convert JSON data to an object
  let users = JSON.parse(this.response);
let output = '';
  for (
var i = 0; i < users.length; i++) {
    output += '<li>' + users.name + ' is ' + users.age + ' years old.'; '</li>'
  }
  document.getElementById('users').innerHTML = output;
}

Finally, we submit the request!

request.send();

Here’s the final code.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JSON Demo</title>
</head>
<body>
  <ul id="users"></ul>
  <script>
    let request = new XMLHttpRequest();
    request.open('GET', 'users.json', true);
      request.onload = function () {
      // Convert JSON data to an object
      let users = JSON.parse(this.response);
      let output = '';
      for (
		var i = 0; i < users.length; i++) {
        output += '<li>' + users.name + ' is ' + users.age + ' years old.'; '</li>'
      }
      document.getElementById('users').innerHTML = output;
    }
        request.send();
  </script>
</body>
</html>

We're nearly done!

But if you open the HTML file, you get an error from the console.

As we call users.json from the file system instead of a real domain (a security protocol for the browser).

So we'll have to run it on a local server to test it locally.

If you installed xampp, go ahead and upload it to your webroot. However, the installation of liveserver via npm would be a simpler solution. Make sure you have installed NodeJS and run npm install-g live server from the directory in which your HTML file is stored. After the installation of the module is complete, you simply run live servers from the same directory and the HTML file will open on a local server.

And our data will print as specified!

Paul is 30 years old.
Sylvia is 38 years old.
Luis is 45 years old.

The Fetch API

We all remember the dreaded XMLHttpRequest we used back in the day to make requests, it involved some really messy code, it didn't give us promises and let's just be honest, it wasn't pretty JavaScript, right? Maybe if you were using jQuery, you used the cleaner syntax with jQuery.ajax().

Well JavaScript has it's own built-in clean way now. Along comes the Fetch API a new standard to make server request jam-packed with promises and all those things we learned to love over the years.

We can use Fetch with our data like so:

fetch('./users.json').then(
	response => {
  		return response.json();
	}).then(
data => {
// Work with your JSON data here..
console.log(data);
}).catch(
err 
=> {
  
// What do when the request fails
  
console.log('The request failed!'); 
});

Using JSON with Query

If you use jQuery on your project, the getJSON) (function can be used to retrieve data.

$(document).ready(function () {
  $.getJSON('users.json', function (data) {
    // Work with your JSON data here..
    console.log(data[0].name);
  });
});

Don’t forget to add jQuery above this function, if you’re testing it out!

We hope this article has helped you to better understand JSON and to see it in action with AJAX! ;-)

 

 

Business vector created by freepik - www.freepik.com
 
by admin Date: 11-02-2019 javascript JSON jQuery hits : 2572  
 
 
 
 

Related Posts