-- online Search!

All About JSON (aka JavaScript Object Notation)

by kirupa   |   filed under JavaScript 101

When it comes to storing, retrieving, or transmitting data, there are a bunch of file formats and data structures that you can use. You've probably used text files, Word documents, Excel spreadsheets, zip files, and so on to deal with the various kinds of data you handle. On the web front, there is one format that reigns supreme over all others. It runs faster. It jumps higher. It has a shinier (and furrier) coat of fur. That format is known as JSON - short for JavaScript Object Notation.

In this article, we are going to learn what JSON can represent and how we turn its text into values our code can use. JSON carries data between programs; it does not require the receiving program to execute JavaScript.

Onwards!

What is JSON?

In JavaScript, you have a way of defining objects using the object literal syntax:

let funnyGuy = {
    firstName: "Conan",
    lastName: "O'Brien",
 
    getName: function () {
        return "Name is: " + this.firstName + " " + this.lastName;
    }
};
 
let theDude = {
    firstName: "Jeffrey",
    lastName: "Lebowski",
 
    getName: function () {
        return "Name is: " + this.firstName + " " + this.lastName;
    }
};
 
let detective = {
    firstName: "Adrian",
    lastName: "Monk",
 
    getName: function () {
        return "Name is: " + this.firstName + " " + this.lastName;
    }
};

If you aren't familiar with this syntax, I highly recommend you read more about it in the Deeper Look at Objects article. It will make understanding and working with JSON objects significantly easier!

On the surface, the object literal syntax looks like a bunch of brackets and colons and weird curly braces that define your object's properties and values. Despite how weird it looks, under the covers, it is fairly descriptive. Many of the common data types you would want to use are available. You can neatly represent their properties and values as key and value pairs separated by a colon. Equally important as all the other stuff I just mentioned, this syntax allows you to have structure and nested values. Overall, it is a pretty sweet way of representing JavaScript objects...in a literal representation!

The JSON format borrows heavily from this object literal syntax, but its rules are not identical. Here is a historical JSON response from the WeatherUnderground API for displaying the weather in my hometown of Seattle:

{
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "conditions": 1
        }
    },
    "current_observation": {
        "image": {
            "url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
            "title": "Weather Underground",
            "link": "http://www.wunderground.com"
        },
        "display_location": {
            "full": "Seattle, WA",
            "city": "Seattle",
            "state": "WA",
            "state_name": "Washington",
            "country": "US",
            "country_iso3166": "US",
            "zip": "98101",
            "magic": "1",
            "wmo": "99999",
            "latitude": "47.61167908",
            "longitude": "-122.33325958",
            "elevation": "63.00000000"
        },
        "observation_location": {
            "full": "Herrera, Inc., Seattle, Washington",
            "city": "Herrera, Inc., Seattle",
            "state": "Washington",
            "country": "US",
            "country_iso3166": "US",
            "latitude": "47.616558",
            "longitude": "-122.341240",
            "elevation": "121 ft"
        },
        "estimated": {},
        "station_id": "KWASEATT187",
        "observation_time": "Last Updated on August 28, 9:28 PM PDT",
        "observation_time_rfc822": "Fri, 28 Aug 2015 21:28:12 -0700",
        "observation_epoch": "1440822492",
        "local_time_rfc822": "Fri, 28 Aug 2015 21:28:45 -0700",
        "local_epoch": "1440822525",
        "local_tz_short": "PDT",
        "local_tz_long": "America/Los_Angeles",
        "local_tz_offset": "-0700",
        "weather": "Overcast",
        "temperature_string": "68.0 F (20.0 C)",
        "temp_f": 68.0,
        "temp_c": 20.0,
        "relative_humidity": "71%",
        "wind_string": "Calm",
        "wind_dir": "NNW",
        "wind_degrees": 331,
        "wind_mph": 0.0,
        "wind_gust_mph": "10.0",
        "wind_kph": 0,
        "wind_gust_kph": "16.1",
        "pressure_mb": "1008",
        "pressure_in": "29.78",
        "pressure_trend": "-",
        "dewpoint_string": "58 F (15 C)",
        "dewpoint_f": 58,
        "dewpoint_c": 15,
        "heat_index_string": "NA",
        "heat_index_f": "NA",
        "heat_index_c": "NA",
        "windchill_string": "NA",
        "windchill_f": "NA",
        "windchill_c": "NA",
        "feelslike_string": "68.0 F (20.0 C)",
        "feelslike_f": "68.0",
        "feelslike_c": "20.0",
        "visibility_mi": "10.0",
        "visibility_km": "16.1",
        "solarradiation": "--",
        "UV": "0",
        "precip_1hr_string": "0.00 in ( 0 mm)",
        "precip_1hr_in": "0.00",
        "precip_1hr_metric": " 0",
        "precip_today_string": "0.00 in (0 mm)",
        "precip_today_in": "0.00",
        "precip_today_metric": "0",
        "icon": "cloudy",
        "icon_url": "http://icons.wxug.com/i/c/k/nt_cloudy.gif",
        "nowcast": ""
    }
}

Ignoring the size of the data returned, there are a lot of similarities between the JSON data you see and the object literal syntax you saw earlier. There are some major differences that you need to be aware of as well, but we'll look at all that boring stuff later. First, let's take a deeper look at what exactly makes up a JSON object.

Looking Inside a JSON Object

A JSON object is nothing more than a combination of property names and their values. That seems pretty simple, but there are some important details that we need to go over in this section.

Property Names

Property names are the identifiers you will use to access a value. Visually, they are the things to the left of the colon character:

{
    "firstName": "Kirupa",
    "lastName": "Chinnathambi",
    "special": {
        "admin": true,
        "userID": 203
    },
    "devices": [
        {
            "type": "laptop",
            "model": "Macbook Pro 2015"
        },
        {
            "type": "phone",
            "model": "iPhone 6"
        }
    ]
}

In this JSON snippet, the property names are firstName, lastName, special, admin, userID, devices, type, and model. Notice how the property names are defined. They are string values wrapped in quotation marks. The quotation mark is an important detail that you don't have to specify in the object literal case for property names, so don't forget to include them when working in the JSON world!

The Values

Each property name maps to a value. JSON represents data, so executable functions and arbitrary object prototypes do not travel with it. The supported value types are:

  • Numbers
  • Strings
  • Booleans (true or false)
  • Objects
  • Arrays
  • Null

Let's map these various types to the example we just looked at earlier.

Strings

The string values are the following highlighted lines:

{
    "firstName": "Kirupa",
    "lastName": "Chinnathambi",
    "special": {
        "admin": true,
        "userID": 203
    },
    "devices": [
        {
            "type": "laptop",
            "model": "Macbook Pro"
        },
        {
            "type": "phone",
            "model": "iPhone XS"
        }
    ]
}

The double quotation marks are a dead giveaway that these values are strings. JSON has its own escaping rules, so don't assume every JavaScript escape is allowed. Double quotes, backslashes, and control characters need appropriate escaping inside a JSON string. An apostrophe can appear directly; \' is not a valid JSON escape. A serializer handles these details while preserving the string's content.

Numbers

Our lone representative of the number family is the value for the userID property:

{
    "firstName": "Kirupa",
    "lastName": "Chinnathambi",
    "special": {
        "admin": true,
        "userID": 203
    },
    "devices": [
        {
            "type": "laptop",
            "model": "Macbook Pro"
        },
        {
            "type": "phone",
            "model": "iPhone XS"
        }
    ]
}

You can specify decimal values such as 0.204, 1200.23, and 45, as well as exponential notation such as 2e16, 3e+4, and 1.5e-2. A leading zero followed by another digit, as in 03.14, is not allowed, and neither are the literal tokens NaN and Infinity. Valid JSON syntax still does not guarantee exact JavaScript Number arithmetic: large integers can lose precision and very large exponents can overflow. Agree on a suitable representation when exact identifiers or measurements matter.

Booleans

Boolean values are easy:

{
    "firstName": "Kirupa",
    "lastName": "Chinnathambi",
    "special": {
        "admin": true,
        "userID": 203
    },
    "devices": [
        {
            "type": "laptop",
            "model": "Macbook Pro"
        },
        {
            "type": "phone",
            "model": "iPhone XS"
        }
    ]
}

The values can be true or false, spelled in lowercase. Quoting either word changes it into a string. That difference matters when a caller uses the field as a condition, because a nonempty string is truthy even if its text says false.

Objects

This is where things get a little interesting:

{
    "firstName": "Kirupa",
    "lastName": "Chinnathambi",
    "special": {
        "admin": true,
        "userID": 203
    },
    "devices": [
        {
            "type": "laptop",
            "model": "Macbook Pro"
        },
        {
            "type": "phone",
            "model": "iPhone XS"
        }
    ]
}

Objects contain a collection of property names and values, and they are separated from the rest of your content with curly brackets. See? Wasn't that a little interesting?

Arrays

Our devices property represents an array:

{
    "firstName": "Kirupa",
    "lastName": "Chinnathambi",
    "special": {
        "admin": true,
        "userID": 203
    },
    "devices": [
        {
            "type": "laptop",
            "model": "Macbook Pro"
        },
        {
            "type": "phone",
            "model": "iPhone XS"
        }
    ]
}

Arrays store an ordered collection of zero or more values that you can iterate through, and they are separated by the bracket notation. Inside an array, you can use any of the JSON types we've seen so far...including other arrays!

Null

The last data type is also the most boring one:

{
    "foo": null
}

Your JSON values can be null. This is an explicit value, different from leaving a property out. For example, a patch contract might use null to clear an existing setting and omission to leave it unchanged. A numeric zero is a real value too, so don't use it to hide a missing measurement.

Reading JSON Data

I admit it. The previous section was extremely dull, but there is some good news! Given how boring what you just saw was, this section is by comparison going to seem a whole lot more exciting than it really is. Yay!

Once JSON text has been parsed, we work with ordinary JavaScript values. For an object, we can read properties with dot notation (property.propertyFoo) or bracket notation (property["propertyFoo"]). Parsing alone does not establish that the result has the fields our application expects, so validate that contract before following a nested property path.

To help explain all this, let's use the following example:

let exampleJSON = {
  "firstName": "Kirupa",
  "lastName": "Chinnathambi",
  "special": {
      "admin": true,
      "userID": 203
  },
  "devices": [
      {
          "type": "laptop",
          "model": "Macbook Pro"
      },
      {
          "type": "phone",
          "model": "iPhone XS"
      }
  ]
};

To read the value stored by firstName, you can do either of the following:

exampleJSON.firstName
exampleJSON["firstName"]

Both lines return Kirupa. Either notation works for this fixed property name, but bracket notation also handles computed names and names that cannot be written after a dot. My personal preference for names like this one is dot notation, so that is what we'll use in the following snippets.

Similar to what you saw earlier, to access the value stored by lastName, you can do this:

exampleJSON.lastName

For simple properties that store simple values, life is pretty simple. The only very VERY minor complication you'll run into is when working with more complex values made up of Objects and Arrays. To read a value stored inside an Object, just keep dotting into each property until you reach the property that stores the value you are interested in.

Here is what trying to access the value stored by the userID property will look like:

exampleJSON.special.userID

Arrays are no different, but you will eventually have to switch into array notation once you get to the property that stores your array values. If we wanted to access the model value of the first device in the devices array, we can type something that looks as follows:

exampleJSON.devices[0].model

Because the devices property refers to an array, you can also perform stereotypical array-like operations such as the following:

let devicesArray = exampleJSON.devices;

for (let i = 0; i < devicesArray.length; i++) {
  let type = devicesArray[i].type;
  let model = devicesArray[i].model;

  // do something interesting with this data!
}

The parsed values can be strings, numbers, objects, arrays, Booleans, or null. JSON does not require an object at the top level, so a successful parse could also produce a number or a string. Check the shape and permitted values your application needs rather than treating successful parsing as schema validation.

Parsing JSON Text into JavaScript Values

In our example, exampleJSON is already a JavaScript object. Its data could be represented in JSON, but the variable does not contain JSON text that needs parsing.

A response API might instead return the raw JSON text. That text can be perfectly valid JSON while still needing to be parsed before we use its nested values. Check what the API returns instead of deciding from how the response looks in a log.

The JSON.parse method converts JSON text into JavaScript values. In this callback example, we expect HTTP status 200 and a nonempty region string before calling selectInitialState. An unexpected status, malformed JSON, and an invalid region need separate handling:

function processRequest(e) {
  if (xhr.readyState !== 4) return;
  if (xhr.status !== 200) {
    console.error("Unexpected response status.", xhr.status);
    return;
  }
  let response;
  try {
    response = JSON.parse(xhr.responseText);
  } catch (error) {
    if (!(error instanceof SyntaxError)) throw error;
    console.error("The response was not valid JSON.", error);
    return;
  }
  if (response === null || typeof response !== "object" ||
      Array.isArray(response) || typeof response.region !== "string" ||
      response.region.trim() === "") {
    console.error("Expected a response with a nonempty region string.");
    return;
  }
  selectInitialState(response.region);
}

The highlighted line parses the text. The catch handles malformed JSON, while the following check handles the region contract; an error from later processing is not automatically a JSON syntax error. If a library already returns parsed values, use those values and validate them directly. Parsing them again is not an extra safety check.

Writing JSON Data?

Writing JSON is useful in browser code too, whether we are sending a request or storing structured data as text. Here is how we can serialize the object from our earlier example:

let requestBody = JSON.stringify(exampleJSON);
console.log(requestBody);

The result is JSON text, not an automatically sent request. Serialize the intended value once at the boundary that needs text. Serializing that text again describes a string instead of the original object. A JSON round trip also does not preserve object identity, custom methods, or every JavaScript value, so check that the supported data matches what you need to retain.

Conclusion

At one point in time, this article would have been focused on XML. Even today, XML is still widely popular as a file format for storing or communicating information. Only in a world where the web browser is king (aka the world that we live in) is where JSON is extremely popular. That doesn't mean that JSON doesn't exist in other situations. App configuration for both web as well as non-web situations are increasingly using JSON as their way of representing data. Who knew?!!

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--