Skip to content

JavaScript JSON

JSON (JavaScript Object Notation) is a lightweight text-based format for storing and transporting data. It’s commonly used for exchanging data between a server and a web application, or for configuration files.

  • JSON stands for JavaScript Object Notation.
  • It’s a lightweight data-interchange format.
  • JSON is language-independent, though its syntax is derived from JavaScript object literal syntax.
  • It’s designed to be human-readable and easy for machines to parse and generate.

While JSON’s syntax is a subset of JavaScript’s object literal syntax, JSON itself is purely a string format. Data represented in JSON format can be easily read and generated by virtually any programming language.

This JSON example defines an object with an “employees” property, which is an array of three employee objects:

{
"employees": [
{
"firstName": "John",
"lastName": "Doe",
"department": "Engineering"
},
{
"firstName": "Anna",
"lastName": "Smith",
"department": "Marketing"
},
{
"firstName": "Peter",
"lastName": "Jones",
"department": "Sales"
}
]
}

The JSON format is syntactically very similar to JavaScript object literals. This similarity makes it straightforward for JavaScript programs to convert JSON data into native JavaScript objects and vice versa.

  • JSON.parse(): A built-in JavaScript function that converts a JSON string into a JavaScript object.
  • JSON.stringify(): A built-in JavaScript function that converts a JavaScript object into a JSON string.
  • Data is in name/value pairs (e.g., "name": "value").
  • Keys (names) must be strings, enclosed in double quotes.
  • Values can be strings (in double quotes), numbers, booleans (true or false), arrays (in square brackets []), or other JSON objects (in curly braces {}).
  • 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:

"firstName": "John"
Important: In JSON, keys (names) must be enclosed in double quotes. In JavaScript object literals, quotes around keys are often optional if the key is a valid identifier.

JSON objects are written inside curly braces {}. They can contain multiple name/value pairs:

{"firstName": "John", "lastName": "Doe"}

JSON arrays are written inside square brackets []. An array can contain a list of values, including JSON objects:

"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]

In the example above, the value associated with the “employees” key is an array. This array contains three JSON objects, each representing an employee.

A common use of JSON is to fetch data from a web server (API) and display it on a web page. The fetched data is typically a JSON string.

First, you have a JavaScript string containing JSON formatted data:

const jsonString = '{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}';

Then, use the JavaScript built-in function JSON.parse() to convert the JSON string into a JavaScript object:

const data = JSON.parse(jsonString);

Finally, you can use the new JavaScript object in your page. For example, to display the first name and last name of the second employee:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON Parsing Example</title>
</head>
<body>
<p id="demo"></p>
<script>
const jsonString = '{\n "employees": [\n { "firstName":"John" , "lastName":"Doe" },\n { "firstName":"Anna" , "lastName":"Smith" },\n { "firstName":"Peter" , "lastName":"Jones" }\n ]\n }';
const data = JSON.parse(jsonString);
const displayElement = document.getElementById("demo");
if (displayElement && data.employees && data.employees.length > 1) {
displayElement.textContent =
data.employees[1].firstName + " " + data.employees[1].lastName;
} else {
// Handle cases where the element or data is not as expected
console.error("Could not display employee data.");
}
</script>
</body>
</html>

For more in-depth information on handling asynchronous data fetching (e.g., from APIs), you can explore the Fetch API or libraries like Axios. These are covered in more advanced JavaScript topics.