Introduction
Hey there, Dev! π If you're reading this article, chances are you already know that JSON (JavaScript Object Notation) is the language of modern data exchange. JSON has gained tremendous popularity due to its simplicity, versatility, and widespread support across various programming languages and platforms. Whether you're a seasoned developer or just starting your journey, understanding JSON is essential for effective data manipulation and integration. In this article, we'll dive into the syntax, structure, and practical exercises of JSON, exploring how it simplifies data interchange and equipping you with the skills to handle JSON data effectively. Letβs dive right into it π
What is JSON
JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format and the cool thing about it is that it is easy to read and write for humans and machines. JSON is a popular data interchange format for web applications.
Syntax
JSON is composed of key-value pairs. Each pair consists of a key (in double quotes) followed by a colon :, and then the corresponding value. Letβs see an example for easier understanding.
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
From the example above, we have a JSON object representing a person's information. The object contains three key-value pairs: name with the value John Doe, age with the value 30, and city with the value New York.
It is important to know how to save a JSON file which is using the .json. Using the example above you can save the JSON file as personal_info.json.
Now that we know what the syntax is, Letβs look at the data types in JSON.
Data Types in JSON
-. JSON Strings
A string in JSON is a sequence of characters that are enclosed in double-quotes. The characters can be letters, numbers, symbols, and spaces.
Here is an example of a JSON string ππ½
"name": "John"
- JSON Strings
A number in JSON is a real number. The numbers can be integers, floats, or decimals.
Here is an example of a JSON number ππ½
"age": 25,
"pi": 3.14159
- JSON Booleans
A boolean in JSON is a value that can be either true or false.
Here is an example of a JSON boolean ππ½
"isReading": true
- JSON Objects
An object in JSON is a collection of properties. The properties are key-value pairs. The key is a string, and the value can be a string, number, object, or array.
Here is an example of a JSON object ππ½
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main Street",
"city": "Anytown",
"state": "CA",
"zip": "91234"
}
}
In this example, the object has three properties: name, age, and address. The name property has a string value, the age property has a number value and the address property is an object.
- JSON Arrays
An array in JSON is a collection of values. The values can be strings, numbers, objects, or arrays.
Here is an example of a JSON array ππ½
"grades": [90, 85, 95]
In this example, the array has three values: 90, 85, and 95.
**- JSON Null**
The null value in JSON represents a value that is undefined or unknown.
Here is an example of a JSON null value ππ½
"middleName": null
I know you must be very familiar with these data types we just talked about, but knowing the data types in JSON is important because it allows you to correctly interpret and handle the data in your applications very easily.
JSON Vs JavaScript Objects
It is important to point out the difference between JSON and JavaScript objects so that youβll not be as confused as me when I first learned about it π
JSON
I know you already know what JSON is by now. But letβs see it in comparison to JavaScript objects.
JSON is a data format that is often used for data interchange between systems. It is language-independent and can be understood by many programming languages.
In JSON, all keys must be enclosed in double-quotes.
JSON requires strict adherence to its syntax rules.
Letβs see an example for better understanding ππ½
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
}
In this JSON example, the data is represented as a string. Keys are enclosed in double quotes, and values can be strings, numbers, objects, or other JSON data types.
JavaScript Objects
JavaScript objects are native to the JavaScript programming language and are used for data manipulation within JavaScript programs.
JavaScript objects allow for unquoted keys.
JavaScript objects allow for more flexibility.
const person = {
name: "John Doe",
age: 30,
address: {
street: "123 Main St",
city: "New York",
country: "USA"
}
};
In this JavaScript object example, the data is represented using JavaScript syntax. Keys are not enclosed in quotes, but values can still be strings, numbers, objects, or any valid JavaScript data type.
You can see that they are kind of opposite to each.
_
π‘ It's important to note that while the JSON syntax and JavaScript object syntax are similar, JSON requires keys to be enclosed in double quotes, whereas JavaScript objects allow for unquoted keys. Additionally, JSON is a data interchange format and requires parsing and stringification when interacting with it in programming languages, whereas JavaScript objects can be directly used and manipulated within JavaScript code._
JSON Parsing and Serialization
JSON parsing and serialization are important concepts when working with JSON data. Letβs take a detailed look at each of them ππ½
JSON Parsing
JSON parsing refers to the process of converting a JSON string (JSON) into a native data structure (JavaScript Object) that can be used in your programming language. This allows you to extract and access the individual values stored in the JSON data.
Donβt worry yourself if you are finding it hard to wrap your head around it. Letβs see an example for a better understanding ππ½
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
}
The example above is a JSON string representing a person's information. Now to parse this JSON string, you would use the appropriate function provided by your programming language's JSON library. But since we are working with JavaScript, Here's how it is going to look like ππ½
const jsonString = '{"name":"John Doe","age":30,"address":{"street":"123 Main St","city":"New York","country":"USA"}}';
const person = JSON.parse(jsonString);
console.log(person.name); // Output: John Doe
console.log(person.age); // Output: 30
console.log(person.address.city); // Output: New York
From the code above, JSON.parse() is used to parse the JSON string jsonString into a JavaScript object (person). After parsing, you can access the individual values using dot notation (person.name, person.age, etc.). Hope it makes total sense now π
JSON Serialization
JSON serialization is basically the opposite of JSON parsing. It is the process of converting a native data structure (such as an object or an array) into a JSON string. And it is most useful when you need to send or store JSON data.
Continuing with the previous example, let's serialize the person object back into a JSON string ππ½
const person = {
name: "John Doe",
age: 30,
address: {
street: "123 Main St",
city: "New York",
country: "USA"
}
};
var jsonString = JSON.stringify(person);
console.log(jsonString);
The JSON.stringify() function is used to serialize the person object into a JSON string. The resulting JSON string can be logged out or used for various purposes, such as sending it over the network or storing it in a file. Here is what the output will be like ππ½
{"name":"John Doe","age":30,"address":{"street":"123 Main St","city":"New York","country":"USA"}}
Pretty easy right? π
π‘ By understanding JSON parsing and serialization, you can effectively work with JSON data in your applications. Parsing allows you to extract data from a JSON string and work with it programmatically, while serialization enables you to convert native data structures into JSON for transmission or storage.
π¨π½βπ» Hands-On Exercise
Letβs build a very easy exercise with what weβve discussed so far. ππ½
Exercise: Create a Personal Information JSON File.
Here are the things we need in other to achieve the task ππ½
Create a JSON file named
personal_info.json
to store your personal information.-
Populate the JSON file with your personal details. Include properties such as:
- "name": Your full name as a string.
- "age": Your age as a number.
- "email": Your email address as a string.
- "address": Your address as an object with properties like "street", "city", "state", "zip", and "country".
You can use this data in the personal_info.json
file instead ππ½
{
"name": "John Doe",
"age": 25,
"email": "johndoe@example.com",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001",
"country": "USA"
}
}
- 3. Write a JavaScript program to read and display your personal information from the
personal_info.json
file.- Use the Fetch API or an appropriate method in your programming language to read the contents of the JSON file.
- Parse the JSON data and store it in a variable.
- Access the individual properties of your personal information and display them on the console or in a user-friendly format.
I know you are like βWhat is Fetch API doing in the exercise?β. The answer to your question is that since we are storing the data in a separate file (personal_info.json
), we need to fetch it so that we can have access to all the data in the file. But if you do not know what Fetch API is, you can go quickly go through this article before starting the exercise ππ½.
Here is the solution to the Exercise to compare with your own solution ππ½
// Fetch the contents of the JSON file
fetch('personal_info.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
// Access the individual properties and display them
console.log('Name:', data.name); // John Doe
console.log('Age:', data.age); // 25
console.log('Email:', data.email); // johndoe@example.com
console.log('Address:', data.address); // {street: '123 Main St', city: 'New York', state: 'NY', zip: '10001', country: 'USA'}
})
.catch(error => {
console.error('Error:', error);
});
Letβs break down the explanation ππ½
The code starts by using the
fetch
function to make an HTTP request to retrieve the contents of the JSON file named "personal_info.json".The
fetch
function returns a promise that resolves to the response object representing the server's response to the request.The first
.then()
method is called on the promise returned byfetch
. It checks if the response was successful (response.ok
checks if the response status is within the 200-299 range). If the response is not successful, an error is thrown with a descriptive message including the status code.If the response is successful, the second
.then()
method is called, which extracts the JSON data from the response using the.json()
method. This method returns another promise that resolves to the parsed JSON data.The callback function in the second
.then()
method receives the parsed JSON data as thedata
parameter. In this example, the individual properties of the JSON object are accessed (data.name
,data.age
,data.email
,data.address
) and logged to the console for display.If any error occurs during the fetch request or JSON parsing, the
.catch()
method is called, and the error is logged to the console.
_
π‘ Just to push yourself more, you can extract the data inside theaddress
object._
Conclusion
Congrats on getting to this part of the article π π. There are some things that I could not cover in this article that are a little bit advanced. But this article will definitely show you the basics of how JSON works. Till next week guys. Have a wonderful weekend π
Top comments (5)
Thanks chantal. I'm really happy that you found the article helpful
my pal JSON should be your friend too
dev.to/rickdelpo1/my-pal-json-shou...
This is a really helpful write up, thank you
thanks bro. I really appreciate