Intro to XML and JSON #6: JSON
Tags: xml, json, tutorial, beginners
Published: 2019-04-26 18:29:46

---
title: Intro to XML and JSON #6: JSON
description:  "Deep Dive:  Read & Write JSON"
published: true
tags: xml,json,tutorial,beginners
series: "Intro to XML and JSON"
cover_image: https://katiekodes.com/images/xml-json-intro-header-en.png
canonical_url: https://katiekodes.com/intro-xml-json-6/
---

We’ve seen JSON from a “[30,000-foot view](https://dev.to/katiekodes/intro-to-xml-and-json-56co).”  
  
We understand [what kind of data](https://dev.to/katiekodes/intro-to-xml-and-json-2-datas-shape-3iji) JSON can help us with.  
  
**Let’s learn how to write JSON!**

_(And let’s talk a lot about octopi. 🐙 Thanks, Marijn Haverbeke.)_

* * *

Warning: I’m afraid JSON might be getting the short end of the stick by coming after XML.

XML and JSON are both great standards for writing data shaped like “lists of lists,” and both deserve to be introduced _as they are_, not as a “compare and contrast” to the other.

I _do_ want you to leave this series capable of comparing, contrasting, and translating between the two.

However, I **fear that I will make JSON seem far more complicated than it is** by introducing it as “compared to XML,” because I’m going to have to spend a lot of time talking about XML things you _can’t_ do (often before covering JSON things you _can_ do).

Please know that JSON is typically considered “simpler” to read and write than XML. To see explanations of JSON that introduce it in its own right, without defining it in comparison to XML, visit the links in Additional Resources at the bottom of this article.

Finally, as with XML, we’ll talk a lot about items, keys, and values, so [click here](https://katiekodes.com/intro-xml-json-2/#items-keys--values) if you need a refresher before starting today’s lesson.

* * *

![](https://katiekodes.com/images/booksmany.jpg)

## Posts In This Series

1. Overview {% link https://dev.to/katiekodes/intro-to-xml-and-json-56co %}
2. Tables vs. Lists _(this post)_ {% link https://dev.to/katiekodes/intro-to-xml-and-json-2-datas-shape-3iji %}
3. XML 1 {% link https://dev.to/katiekodes/intro-to-xml-and-json-3-xml-items-keys-1m7i %}
4. XML 2 {% link https://dev.to/katiekodes/dying-intro-to-xml-and-json-4-xml-values-5bi1 %}
5. XML 3 {% link https://dev.to/katiekodes/intro-to-xml-and-json-5-xml-csv-conversions-45n5 %}
6. JSON {% link https://dev.to/katiekodes/intro-to-xml-and-json-6-json-30h3 %}
7. Recap {% link https://dev.to/katiekodes/intro-to-xml-and-json-7-recap-and-real-world-use-5586 %}

* * *

![](https://katiekodes.com/images/bouquet-wide.jpg)

## Viewing “Pretty” XML & JSON

We’ll have a lot of examples in this series. I recommend that you edit them and play with seeing them in a “pretty” format! [XML](http://codebeautify.org/xmlviewer), [JSON](http://codebeautify.org/jsonviewer) – paste & click “Tree View”.

Warning: only put sample data into the “beautifier” links above. **Never** put your company’s confidential data into a stranger’s web site.

* * *

![](https://upload.wikimedia.org/wikipedia/commons/e/ef/Json_obtenido.jpg)

## Items in JSON: the “Object”

The punctuation that JSON uses to define the beginning and end of an “object” is a set of “curly braces.” It looks like this:

```json
{}
```

The fact that the pair of curly braces _exists in your text file_ means that it _exists as a conceptual “ **item** ” in your data_.

* * *

### Empty Elements

It doesn’t matter whether or not there’s anything typed between the curly braces.

The “object” is still a conceptual item that “exists” in your data, simply because you bothered to create a pair of curly braces to represent it.

If it doesn’t have anything between the braces, you can think of it a little like a row full of nothing but commas in a CSV file.

It’s still there!

It’s just blank.

* * *

![](https://katiekodes.com/images/octopus-wide.jpg)

## A uniquely JSON concept: the “List”

It’s hard to explain exactly what a JSON “list” is _(a.k.a. an “array”)_, when thinking about “items,” “keys,” and “values,” because it’s not quite any of them.

It certainly doesn’t appear in XML or CSV.

And yet, there’s a very clear punctuation standard for writing a JSON list.

The punctuation that JSON uses to define the beginning and end of a “list” is a set of “square brackets.” It looks like this:

```json
[]
```

As with empty objects, it’s valid to include an empty list in your data set. _(Whether you think it’s meaningful to do so is a business question you’ll have to answer.)_

I’m going to go into more detail later about how and when to take advantage of “lists” in JSON, so don’t get too caught up in this yet.

Nevertheless, I’d like to show you a quick preview of how lists are used in JSON.

Remember our [“birthday ideas list” from the second article](https://katiekodes.com/intro-xml-json-2/#example-1)?

I would probably put Ridhi’s “birthday” & “collection” **key-value pairs** into a JSON object _(Ridhi being the “item”)_ like this:

```json
{
	"Bday" : "Sep. 16",
	"Collection" : "frogs"
}
```

See how every **value** _(e.g. “frogs”)_ inside an **object** _(e.g. this representation of Ridhi)_ is **labeled by a unique key** _(e.g. “Collection”)_?

Like the “attributes” that can go inside the opening tag of an XML element, JSON key-value pairs within an “object” have have _unique_ keys.

That leaves us in a bit of a pickle _(no pun intended)_ when it comes to describing Dan’s _two_ favorite foods: wine & pickles.

What are we going to do? Call them “food 1” & “food 2?”

```json
{
	"food 1" : "wine",
	"food 2" : "pickles"
}
```

Yuck. That’s almost as ugly as trying to make a CSV file out of our “friends list” was.

Instead, we can use a JSON _list_ to contain _all_ of the values that we might want to label “food”:

```json
[
	"wine",
	"pickles"
]
```

See how nice it is not to have to come up with a unique key name for each food Dan likes?

_That’s_ what JSON lists are for!

The entire object representing Dan could look like this:

```json
{
	"Bday" : "Jan. 27",
	"Food" :
		[
			"wine",
			"pickles"
		]
}
```

I like the way Marijn Haverbeke explains lists in a book called Eloquent JavaScript _(images also from the book)_:

[Marijn on objects](https://eloquentjavascript.net/2nd_edition/04_data.html#p_FolCMJfte3):

> “You may think of objects as octopuses with any number of tentacles, each of which has a name tattooed on it.”
> 
> ![](https://eloquentjavascript.net/2nd_edition/img/octopus-object.jpg)

[Marijn on lists](https://eloquentjavascript.net/2nd_edition/04_data.html#p_Rl8msr9DUz) _(a.k.a. “arrays”)_:

> “Arrays, then, are just a kind of object specialized for storing sequences of things. … You can see them as long, flat octopuses with all their tentacles in a neat row, labeled with numbers.”
> 
> ![](https://eloquentjavascript.net/2nd_edition/img/octopus-array.jpg)

Therefore, in our data, “ **Dan** ” is one octpus whose “ **food** ” tentacle is holding another octopus. The inner-octopus has _implied_ numeric labels on its tentacles, and its tentacles are holding things like “ **wine** ” and “ **pickles**.”

* * *

![](https://katiekodes.com/images/keys_jumbled-wide.jpg)

## “Keys” & their “Values”

Indicating “key-value pairs” to describe a JSON **object** _(or “ **item** “)_ is a bit like [the second _(“attributes”)_ approach to indicating them in XML](https://katiekodes.com/intro-xml-json-3/#keys--their-values---approach-2-attributes).

- As with XML attributes, you are not allowed to use a key more than once to describe any given item _(although you are free to reuse it again elsewhere)_.
- **However** , unlike XML attributes, in JSON you **are** allowed to nest things inside the values of these key-value pairs. In fact, in JSON, it’s highly encouraged!

The punctuation for JSON key-value pairs is also slightly different than it is with XML attributes:

> 1. A key-value pair is connected in JSON with a **colon** (“`:`”).  
_(In XML, an equals sign.)_
> 2. The “ **key** ” to a JSON attribute is supposed to be in **quotes**.  
_(In XML, it shouldn’t be.)_
> 3. The “ **value** ” to a JSON attribute _does **not**_ have to be in **quotes**.  
_(In XML, the “values” of “attributes” have to be in quotes.)_
>   - You only include quotes around a JSON “value” to indicate that it’s “definitely text.”  
`5` is the number 5, but `'5'` is the textual representation of that number.
>   - Numbers and the special keyword `null` can be more easily interpreted as special values by JSON-reading tools if you leave off the quotes _(although be careful not to include commas in the numbers if you’re not putting them in quotes!)_.
>   - A JSON attribute’s value can even be **another JSON object** or **a JSON list**.  
_(We’ll get to that in a minute – it’s pretty powerful.)_
> 4. You separate key-value pairs from each other with **commas** in JSON.  
_(In XML, you use whitespace.)_

Here again is our “Ridhi” object, with its two key-value pairs:

```json
{
	"Bday" : "Sep. 16",
	"Collection" : "frogs"
}
```

Whereas in XML’s “attributes” approach to listing key-value pairs, Ridhi might have looked like this:

```xml
<Ridhi Bday="Sep. 16" Collection="frogs"/>
```

* * *

![](https://katiekodes.com/images/russiandolls-wide.jpg)

### Nesting

Because JSON allows us to be more flexible with the contents of “values” than XML’s attributes notation allows, we can do this with Dan in JSON:

```json
{
	"Bday" : "Jan. 27",
	"Food" :
		[
			"wine",
			"pickles"
		]
}
```

This would have been invalid XML:

```xml
<Dan Bday="Jan. 27" Food=<wine/><pickles/> />
```

Instead, we would have had to use XML’s first approach for indicating key-value pairs _(“items within items”)_ to represent Dan’s food preferences:

```xml
<Dan Bday="Jan. 27">
	<food>wine</food>
	<food>pickles</food>
</Dan>
```

* * *

![](https://katiekodes.com/images/catfight.jpg)

### XML vs. JSON = different structures

As you can see, the structure of JSON is **noticeably different** from XML.

Even though XML and JSON are quite similar, and even though they’re designed to represent the same shape of data, their slight differences mean that you make pretty different structural decisions about how to write them.

Such differences might even impact your choice of XML vs. JSON.

These differences also mean that when you’re reading someone else’s data, if they provide it to you in both XML and JSON, you should be prepared for the data to be **structured differently** between the two files they provide you – _even if the two files represent the same real-world data_.

* * *

![](https://katiekodes.com/images/blankbusinesscard.jpg)

## JSON = BYON (“bring your own names”)

Have you noticed yet that JSON “objects” don’t have names?

I keep saying “the Ridhi object” or “the Ridhi octopus,” but there’s nothing in it that actually says “Ridhi!”

```json
{
	"Bday" : "Sep. 16",
	"Collection" : "frogs"
}
```

XML elements and JSON objects both represent the concept of an “item,” but XML elements have names and JSON objects don’t.

If you want a JSON object named, you’ll have to do it yourself.

For example, something that you could represent in XML like this:

```xml
<Shirt Color="" Fabric=""></Shirt>
```

Might have to become this in JSON:

```json
{
 "type" : "Shirt",
 "Color" : null,
 "Fabric" : null
}
```

See how we took advantage of the fact that the word “ **type** ” wasn’t otherwise needed as the name of a “key” and staked a claim on it?

All we’re doing to “name” JSON objects is making up a new key-value pair and adding it to the object _(preferably as the first one, for human readability)_.

We could do something similar for Ridhi:

```json
{
	"Name" : "Ridhi",
	"Bday" : "Sep. 16",
	"Collection" : "frogs"
}
```

* * *

![](https://katiekodes.com/images/cowgirls.jpg)

### Names? We don’t need no stinkin’ names!

Not all data needs names. Sometimes, you _know_ what’s in your data.

JSON is more concise than XML when your data doesn’t need names.

- **Q:** How can I tell when names are unnecessary?
- **A:** As follows: 
  - You have a bunch of conceptual “items” back-to-back at the same level of nesting
  - None of them need a “plain-text value” representing what they _truly **are**_
  - All of them just contain key-value pairs describing what they **have**

🚗 🚘 🚙 🚌 🏎️

Let’s go back to representing a fleet of cars.

Here’s some XML representing a fleet of cars, each of which have different sets of key-value traits we care about tracking.

```xml
<RootElement>
 <Car color="blue" trim="chrome" trunk="hatchback"/>
 <Car appeal="sporty" doors="2"/>
 <Car doors="4" color="red" make="Ford"/>
</RootElement>
```

Maybe we already _know_ they’re all cars based on the context of our data.

Maybe it feels silly to call them each “`Car`.”

A nice JSON equivalent might be:

```json
[
 {
  "color" : "blue",
  "trim" : "chrome",
  "trunk" : "hatchback"
 },
 {
  "appeal" : "sporty",
  "doors" : "2"
 },
 {
  "doors" : "4",
  "color" : "red",
  "make" : "Ford"
 }
]
```

* * *

![](https://katiekodes.com/images/ducksmarching.jpg)

## Grammar subtlety: Back-to-back “objects”

You **can’t** simply list JSON objects back-to-back the way you can put XML elements back-to-back.

**This isn’t valid JSON:**

```json
{}
{}
```

Instead, you have to put them inside square-brackets and separate them with commas _(that is, you have to make them members of a **JSON list** )_.

_(Tip: Remember not to put a comma after the last one, since nothing comes next. Messing up the commas is an easy copy/paste mistake when you’re editing JSON by hand.)_

**This** is how you show 2 JSON objects at the same level as each other:

```json
[
 {},
 {}
]
```

Note that the line breaks and tabs are for human benefit only. This is the same JSON, written more like you’ll find JSON you download from 3rd parties:

```json
[{},{}]
```

* * *

![](https://katiekodes.com/images/beetroot.jpg)

## Grammar subtlety: Roots

Just like the entirety of a piece of XML must be contained within a single element, the entirety of a piece of JSON **must be contained within a single “octopus.”**

However, you can choose either type of “octopus”:

- An “object” `{}`
- A “list” `[]`

### Examples

This **is** valid JSON – it has an “object” “outer octopus.”

```json
{"name" : "Dan", "Bday" : "Jan. 27"}
```

This is **not** valid JSON – too many “outer octopi.”

```json
{"name" : "Dan", "Bday" : "Jan. 27"}
{"name" : "Ridhi", "Bday" : "Sep. 16"}
```

This **is** valid JSON – it has a “list” “outer octopus.”

```json
[
	{"name" : "Dan", "Bday" : "Jan. 27"},
	{"name" : "Ridhi", "Bday" : "Sep. 16"}
]
```

This is **not** valid JSON _(although there are discussions underway to let it be considered a special exception to the “outer octopus” rule)_:

```json
"wine"
```

This **is** valid JSON – it has a “list” “outer octopus.”

```json
["wine"]
```

This **is** valid JSON – it has a “list” “outer octopus.”

```json
["wine","pickles"]
```

This **is** valid JSON – it has an “object” “outer octopus.”

```json
{"food" : "wine"}
```

This is **not** valid JSON – look carefully … no “outer octopus” at all.

```json
"food" : "wine"
```

* * *

## Lists, again

![](https://katiekodes.com/images/laundrystack-wide.jpg)

Note that the values in the list might be plaintext / numbers / `null` / another list / another item _(“ **object** “)_ / etc.

_(Just like the “value” of a key-value pair in an “object” can be plaintext, numbers, `null`, a list, another object, etc.)_

* * *

![](https://katiekodes.com/images/shoppingbags.jpg)

## Takeaways

1. Both JSON & XML need a single “root” item surrounding the entire contents of a dataset.
2. JSON has “lists,” which requires thinking about “octopi” to understand the role they play in storing data. 
  - Lists are not quite like items, keys, _or_ values in the ways we’ve been referring to these concepts _(although according to “octopus” theory, lists are merely a strange, special kind of item)_.
3. JSON doesn’t name things as explicitly as XML names things. 
  - Whether that’s good or bad depends on your business case.
4. JSON lets you play with the use of quotation marks to indicate how you want values to be treated _(as plaintext, as a number, etc.)_.

* * *

![](https://katiekodes.com/images/booksmany.jpg)

## Additional Resources

- [Squarespace’s introduction to JSON](https://developers.squarespace.com/what-is-json)
- [Matt Doyle’s introduction to JSON](https://www.elated.com/json-basics/)
- TutorialsPoint’s JSON series ([1 - syntax](https://www.tutorialspoint.com/json/json_syntax.htm), [2 - data types](https://www.tutorialspoint.com/json/json_data_types.htm), [3 - comparison to XML](https://www.tutorialspoint.com/json/json_comparison.htm))
- [W3Resource’s quick-reference guide to the punctuation involved in JSON](https://www.w3resource.com/JSON/structures.php)
- [Mozilla’s introduction to JSON for JavaScript programmers](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON), which is still an easy read if you’re not a programmer. You can just gloss over the parts where they talk about coding in JavaScript.
- If you’re really computery, JSON’s official specification is doodled in 5 short-but-complex pictures [here](https://json.org/).