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 : 16182  
 
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

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

The Javascript asign() method to merge and clone objects

In this article, we will be covering Object.assign()method in javascript in detail with examples. A javascript object is a collection of key-value pairs. Keys are also known as properties of object. Keys…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

Awesome JavaScript Games and Js Software to create Games

Best sites js13kGames 2019 - Highlights from the js13kGames 2019 competition. js13kGames 2018 - 13 Games in ≤ 13kB of JavaScript. js13kGames 2017 - Build a game in 13kB or less with js13kGames. Adventure Triangle:…

Is JavaScript good for machine learning?

One of the things you always hear when you are talking to someone related to the M.L. world is that, one must learn Python because the vast majority of the…

First steps into JavaScript – a practical guide 3

After we learned the basic ofaccessing DOM elementsandhow to modify them,we are ready for the more exciting parts – handling DOM events. This allows us to make our web way more…

JavaScript: Promises explained with simple real life examples

Handling asynchronous data flows is complex, who hasn't faced codes like this one?: checkWeather('palma de mallorca', (error, weather) => { if (error) throw error; if (weather === 'well') { return checkFlights('palma…

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