DEV Community

Cover image for What is JSON ( Javascript Object Notation ) and how to use it
Henrique Leme de Brito
Henrique Leme de Brito

Posted on • Edited on

What is JSON ( Javascript Object Notation ) and how to use it

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

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:

<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>
Enter fullscreen mode Exit fullscreen mode

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

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

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:

{     
    "cars": [
        {         
            "brand": "Toyota",         
            "model": "Corolla",         
            "year": 2020,         
            "features": {             
                "color": "Blue",             
                "transmission": "Automatic"         
            }     
        }, 
        {         
            "brand": "Toyota",         
            "model": "Corolla",         
            "year": 2021,         
            "features": {             
                "color": "Red",             
                "transmission": "Automatic"         
            }     
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

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

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()
Enter fullscreen mode Exit fullscreen mode

Working with JSON in 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'}}

Enter fullscreen mode Exit fullscreen mode

Working with JSON in 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  
//        )  
//  
//)
Enter fullscreen mode Exit fullscreen mode

Working with JSON in 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"}  

    }  
}
Enter fullscreen mode Exit fullscreen mode

PS: The Java example uses the json library, 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!

Top comments (8)

Collapse
 
httpjunkie profile image
Eric Bishard

Respectfully, and unless I've misunderstood your point???

"Using JSON as a database can lead to performance issues, data integrity problems, and challenges in managing concurrent access to the data"

Is a wild take....

You should really rethink your messaging about considering json as a database, as this article is obviously for newcomers. Of course json itself as a single file store of data is not a good idea, there is an entire industry and purpose and json databases.

The whole issue of json or nosql databases not having indexing it atomicity is a solved problem, ACID is no longer just a feature of relational databases as well with databases like couchbase and others too, you can use ANSI standard SQL to query them.

NoSQL solutions are usually meant to solve a problem that relational databases are either not well suited for, they also have ODM object data modeling (mongoose and ottoman) for both Mongo DB and Couchbase respectively that enable enforcement of schema.

The tired suggestion that there is no use case for nosql just because is one of a lack of understanding and this route of thinking and suggestion to a new developer could lead them down the wrong path using the wrong tool for a job when there might be a much more suitable database option for a specific application.

Even relational databases options like Postgresql and others have JSON data types are for storing JSON data.

Collapse
 
henriqueleme profile image
Henrique Leme de Brito

Thanks for the comment! I think there might have been a misunderstanding. I totally agree with what you've said, but when I mentioned not to use JSON as a database, I was talking about using a single JSON file to store data, not databases that use JSON formats like MongoDB or Couchbase, as you mentioned.

Those NoSQL databases are great and solve many problems that come with using a simple JSON file, offering indexing, ACID transactions, and efficient queries. I totally agree that NoSQL is super useful for many use cases.

But for newcomers, it's important to know that using a single JSON file to store data can lead to performance and management issues. That's why I said that, so beginners use proper databases, whether SQL or NoSQL, to ensure their projects have a solid foundation.

I hope this clarifies what I meant, and sorry for any misunderstanding. Thanks for the feedback, I'll adjust it to be more specific, and feel free to share more suggestions!!!

Collapse
 
vikkio88 profile image
Vincenzo

this would have been really useful in 2007.

Collapse
 
henriqueleme profile image
Henrique Leme de Brito

It totally would have been xD, I know there are plenty of those on the Internet nowadays, but some friends still ask me about problems they have when using JSON, so I decided to write one trying to be as much clear as I could, using some examples and some details

Collapse
 
phenriquesousa profile image
Pedro Henrique

Thank you so much for sharing!

Collapse
 
henriqueleme profile image
Henrique Leme de Brito

Hope it was useful :)

Collapse
 
tracygjg profile image
Tracy Gilmore

Something I bear in mind when preparing data dependent test scripts is, most JS engines find it easier (quicker) to process JSON than regular JS objects. This is largely due to more restrictive syntax of JSON employs.

Collapse
 
vikkio88 profile image
Vincenzo

why do we need another article about json?