Working with JSON in JavaScript

by Janeth Kent Date: 08-04-2020 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[i].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[i].name); 
      	output += '<li>'+users[i].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[i].name + ' is ' + users[i].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[i].name + ' is ' + users[i].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 Janeth Kent Date: 08-04-2020 javascript JSON jQuery hits : 19493  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration