What is JSON ( Javascript Object Notation ) and how to use it
Tags: beginners, json, learning, programming
Published: 2024-06-14 16:26:34

It's pretty common for newcomers in coding to struggle with many **acronyms** around their first weeks, today we'll talk about one that is very common to use in our profession, it's also really easy to understand trust me! In this article we'll talk about what does the JSON acronym mean, how can be used, what it looks like and much more! Allow me to introduce it 

## Table of contents
- [Table of contents](#table-of-contents)
- [What is JSON anyway ? ](#what-is-json-anyway-)
- [Wasn't there a way of data-transport like this before?](#wasnt-there-a-way-of-data-transport-like-this-before)
- [What's the difference between JSON and XML ?](#whats-the-difference-between-json-and-xml-)
- [Is it still worth giving a try to XML?](#is-it-still-worth-giving-a-try-to-xml)
- [Advantages of JSON ](#advantages-of-json)
   * [JSON Syntax](#json-syntax)
   * [JSON Data Types](#json-data-types)
- [Practical example with Cars](#practical-example-with-cars)
   * [Working with JSON in JavaScript](#working-with-json-in-javascript)
   * [Working with JSON in Python](#working-with-json-in-python)
   * [Working with JSON in PHP](#working-with-json-in-php)
   * [Working with JSON in Java](#working-with-json-in-java)

## What is JSON anyway ? 
The **JSON** or "JavaScript Object Notation" is simply a basic format for transporting data that was created in 2000. But when you read the name, you might ask: 

> "If is a JavaScript Object Notation, then I can only use it with JavaScript, right?" - You, 2024

Not really, because since it's light and simple, it becomes easy to read by other languages and, mostly imporant, by people.

> "Well. if is a light and simple way to transport data, then I'll use it as a database" - You, 2024

I wouldn't recommend it ....

Why not? Well, while JSON is great for transporting data because of its simplicity and readability, using a single JSON file as a whole database may not be the best idea. JSON files are not designed to handle large amounts of data efficiently. They lack the indexing, querying, and transactional capabilities of SQL databases like MySQL, PostgreSQL, or NoSQL databases like MongoDB and ScyllaDB. Using a single JSON file as a database can lead to performance issues, data integrity problems, and challenges in managing concurrent access to the data.
## Wasn't there a way of data-transport like this before?

Of course there were. The main language used was XML (Extensible Markup Language), which was designed to be a flexible and customizable markup language. Although is powerful and highly extensible, it can be quite verbose. Each piece of data in XML is surrounded by tags, which can increase file size and complexity, especially in larger documents or data sets.
## What's the difference between JSON and XML ?

JSON and XML are both data serialization formats. JSON is more concise, making it easier to read and faster to parse, which is well suited to the data structures of modern programming languages. XML, on the other hand, is more verbose with its use of explicit start and end tags, supporting a more complex hierarchical structure suitable for applications that require detailed metadata. While JSON is preferred for Web APIs due to its efficiency, XML is preferred in environments that require extensive document markup, such as enterprise applications.

Here is an XML example for comparison:

```xml
<bookstore>   
	<book>     
		<title>Learning XML</title>     
		<author>Erik T. Ray</author>     
		<price>29.99</price>   
	</book>   
	<book>     
		<title>JSON for Beginners</title>     
		<author>iCode Academy</author>    
		<price>39.95</price>   
	</book> 
</bookstore>
```

And now we have the same example, but this time in JSON:

```json
{
  "bookstore": {
    "books": [
      {
        "title": "Learning XML",
        "author": "Erik T. Ray",
        "price": 29.99
      },
      {
        "title": "JSON for Beginners",
        "author": "iCode Academy",
        "price": 39.95
      }
    ]
  }
}
```

## Is it still worth giving a try to XML?

Well, it depends on what your goal is, but in my opinion it's always worth taking a look on something, even if you don't intend to use it, just to get an idea of what it is and how it's used, you might come across a problem that XML can help you with, who knows.
## Advantages of JSON 

So as you have seen, the main reason for using JSON is its ability to be readable, along with a few others:
- **Easy to Read**: JSON has a clear and straightforward structure.
- **Easy to Parse**: Its simple syntax makes it easy for computers to parse.
- **Compact**: JSON tends to be more lightweight, saving space and bandwidth.
- **Universal**: Widely supported by various programming languages and platforms, used by major companies like Google and Twitter.

### JSON Syntax

The JSON syntax is straightforward and without much secret, following some basic rules:

1. **Data is in name/value pairs**: Each data element in JSON is represented as a key (or name) and value pair, separated by a colon.
2. **Data is separated by commas**: Multiple key-value pairs within an object are separated by commas.
3. **Curly braces hold objects**: An object in JSON is enclosed within curly braces `{}`.
4. **Square brackets hold arrays**: An array in JSON is enclosed within square brackets `[]`.

But it is easier for you to see than to read, so here are some examples for you, along with the definition of each type

### JSON Data Types

JSON supports the following data types:

-  **String**: A sequence of characters, enclosed in double quotes.
	 `"name": "John Doe"`
- **Number**: Numeric values, can be integers or floating-point.
	`"age": 30`
- **Object**: A collection of key-value pairs, enclosed in curly braces.
	`"address": {     "street": "123 Main St",     "city": "Anytown" }`
- **Array**: An ordered list of values, enclosed in square brackets.
	`"courses": ["Math", "Science", "History"]`
- **Boolean**: True or false values.
	`"isStudent": false`
- **Null**: Represents a null value.
	`"middleName": null`

And no, you can't comment in a JSON :D 

## Practical example with Cars

Let's say you want to keep records of cars and their details. Here's an example of how these records can be organized in JSON:

```json
{     
	"cars": [
		{         
			"brand": "Toyota",         
			"model": "Corolla",         
			"year": 2020,         
			"features": {             
				"color": "Blue",             
				"transmission": "Automatic"         
			}     
		}, 
		{         
			"brand": "Toyota",         
			"model": "Corolla",         
			"year": 2021,         
			"features": {             
				"color": "Red",             
				"transmission": "Automatic"         
			}     
		}
	]
}
```

If you want to add more cars, you can simply add more objects to the cars array in the JSON structure.

And this can easily be done by parsing the JSON in a language of your choice and then manipulating it as you wish, here are some examples using the JSON shown earlier to give you a better idea of how to read and parse a JSON file
### Working with JSON in JavaScript

```javascript
const fs = require('fs').promises

const jsonPath = 'C:docs/example/example.json'
const readJsonFile = async () => {

    // Reads the content from the JSON and ensure is read as a string
    const jsonContent = await fs.readFile(jsonPath, 'utf-8')
    // Converts the JSON into a javascript object
    const data = JSON.parse(jsonContent)
    
    console.log(data.cars[0])
    //Output: { brand: "Toyota", model: "Corolla", year: 2020, features: { color: "Blue", transmission: "Automatic", }, }

    console.log(data.cars[1])
    //Output: { brand: "Toyota", model: "Corolla", year: 2021, features: { color: "Red", transmission: "Automatic", }, }

}
readJsonFile()
```
### Working with JSON in Python

```python
import json  
  
#Reads the JSON file  
with open('C:docs/example/example.json', 'r') as jsonFile:  
    #Parse the JSON content  
    jsonContent = json.load(jsonFile)  
  
print(jsonContent['cars'][0])  
#Output: {'brand': 'Toyota', 'model': 'Corolla', 'year': 2020, 'features': {'color': 'Blue', 'transmission': 'Automatic'}}  
print(jsonContent['cars'][1])  
#Output: {'brand': 'Toyota', 'model': 'Corolla', 'year': 2021, 'features': {'color': 'Red', 'transmission': 'Automatic'}}

```

### Working with JSON in PHP

```php
<?php  
$jsonPath = 'C:docs/example/example.json';  
// Reads the content from the JSON  
$contents = file_get_contents($jsonPath);  
  
// Converts the JSON content into a PHP Object  
$jsonContent = json_decode($contents);  
  
print_r($jsonContent->cars[1]);  
// Output: stdClass Object  
// (  
//    [brand] => Toyota  
//    [model] => Corolla  
//    [year] => 2021  
//    [features] => stdClass Object  
//        (  
//            [color] => Red  
//            [transmission] => Automatic  
//        )  
//  
//)
```

### Working with JSON in Java

```java  
package org.example;  
import org.json.JSONArray;  
import org.json.JSONObject;  
  
import java.io.IOException;  
import java.nio.charset.StandardCharsets;  
import java.nio.file.Files;  
import java.nio.file.Paths;  
  
public class Main {  
    public static void main(String[] args) throws IOException {  
        String jsonFilePath = "C:docs/example/example.json";  
        // Reads the content from the file and converts into a string  
        String jsonContent = Files.readString(Paths.get(jsonFilePath), StandardCharsets.UTF_8);  
  
        // Converts the string content into a JSON Object  
        JSONObject jsonExample = new JSONObject(jsonContent);  
  
        JSONArray cars = jsonExample.getJSONArray("cars");  
  
        System.out.println(cars.get(0));  
        // Output: {"features": {"transmission":"Automatic","color":"Blue"},"year":2020,"model":"Corolla","brand":"Toyota"}  
        System.out.println(cars.get(1));  
        // Output: {"features":{"transmission":"Automatic","color":"Red"},"year":2021,"model":"Corolla","brand":"Toyota"}  
  
    }  
}
```

PS:  The Java example uses the [json library](https://mvnrepository.com/artifact/org.json/json), if you try it make sure you have it on your dependencies.
## Conclusion

Wrapping your head around JSON might seem a bit tricky at first, but it's actually a piece of cake once you get the hang of it! We've covered what JSON is, how it's used, and why it's so useful.

From understanding its syntax to seeing it in action in different programming languages, you're now ready to dive in and start using JSON in your projects.

If you still have any doubts, feel free to ask me directly. I hope you enjoyed the article - don't forget to like it and share it with that friend who is still struggling with JSON.

Feedback on the article is welcome so I can improve in the next one. Thanks for reading, stay healthy and drink water!