JSON Object vs. JSON Array Explained With Python (+ Errors)

🏷️

This is about JSON objects vs. JSON arrays.

Whether you use a JSON object or a JSON array is a matter of taste.

So if you want to know what the difference between a JSON object and a JSON array is, then this article is for you.

Let’s get started!

What is the difference between JSON Object and JSON Array?

JSON (JavaScript Object Notation) is a format for storing and exchanging data as keys and values. For example, when retrieving the response from an HTTP request.

The difference between a JSON object and a JSON array is just a matter of taste. If you’re in charge of development it’s up to you.

In the following, you will learn exactly what JSON objects and JSON arrays are and how they differ from each other explained with Python.

In Python, working with JSON is best done by converting them to dictionary objects. 

The JSON record format is very concise and does not require duplicate information like XML.

What Is a JSON Object in Python?

Let’s create a JSON object and dictionary in Python:

{  
  "manufacturer": "Tesla Inc.", 
  "model": "Tesla S",
  "engineType": "elecrical",
  "horsePower": "362"
}
car = {  
  "manufacturer": "Tesla Inc.",
  "model": "Tesla S",
  "engineType": "elecrical",
  "horsePower": "362"
}

Here we see almost exactly the same styling on two objects.

The first is a JSON object describing the car, and the second is a Python dictionary with the same values. 

You can pass JSON objects in plain text, which is good and bad. 

The advantage is that it’s easy to read and parse, and the downside is security. 

Deserialization is the process of converting JSON into objects. 

For the Python json standard library, deserialization generates a dictionary output. 

Let’s convert a JSON string to a dictionary:

>> import json
>> st_car = '{"manufacturer": "Tesla Inc.", "model": "Tesla S", "engineType": "elecrical", "horsePower": 362}'
>> js_car = json.loads(st_car)
>> print(js_car)
{'manufacturer': 'Tesla Inc.', 'model': 'Tesla S', 'engineType': 'elecrical', 'horsePower': 362}

After deserializing, you can access the JSON fields as dictionary fields. 

For example, here’s the manufacturer of your car:

>> print(js_car["manufacturer"])  
Tesla Inc.

Here, JSON object is loaded from a string, like a response to an HTTP request. 

You can also load a JSON object from a file using the method json.load.

To save a dictionary into a JSON object, you need to do the reverse of deserialization, called serialization:

>> js_st = json.dumps(js_car)
>> print(js_st)
{'manufacturer': 'Tesla Inc.', 'model': 'Tesla S', 'engineType': 'elecrical', 'horsePower': 362}

When serializing, you can choose how the object will display:

>> js_st = json.dumps(js_car, indent = 4)
>> print(js_st)
{  
  "manufacturer": "Tesla Inc.",  
  "model": "Tesla S",  
  "engineType": "elecrical",  
  "horsePower": 362  
}  

This pretty formatting works great with JSON objects that have lots of nesting.

You can also serialize a JSON object to a file using the method  json.dump.

In the example, we used strings and integers as field values. But JSON is more comprehensive. 

You can use these data types as field values:

  • String: enclosed in double quotes, and may contain escape characters, such as tabulation, line feed, and Unicode characters.
  • Number: including floating-point and exponential numbers.
  • Boolean: true and false.
  • None: the none value.
  • JSON object: another JSON object.
  • JSON array: another JSON array.

The JSON types are converted to Python data types during deserialization as follows:

JSONPython
objectdict
arraylist
stringstr
number (integer)int
number (real)float
trueTrue
falseFalse
nullNone

 And vice versa when they serialized:

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull

What Is a JSON Array in Python?

JSON arrays are structured the same as Python bracketed lists. They can have the same data types as the JSON object field values, including nested arrays. 

Let’s add a battery field to the JSON object above, its value is a JSON array. 

In this array, we will keep track of the Tesla’s battery capacity values:

>> st_car = '{"manufacturer": "Tesla Inc.", "model": "Tesla S", "engineType": "elecrical", "horsePower": 362, "battery": ["100 kWh", "90 kWh", "80 kWh"]}'
>> js_car = json.loads (st_car)

When deserialized, the JSON array becomes a Python list. 

You can refer to the elements of this list by index. 

The JSON array here represents the value of the battery field in the JSON object:

batteries = js_car ["battery"]
>> print(batteries[0])  
100 kWh

You can also pass a JSON array at the highest level of a JSON file or string. Let’s add another car and see what happens:

>> st_cars = '[{"manufacturer": "Tesla Inc.", "model": "Tesla S", "engineType": "elecrical", "horsePower": 362}, {"manufacturer": "Tesla Inc. "," model": "Tesla 3 "," engineType": "elecrical", "horsePower": 346}]'  
>> js_cars = json.loads(st_cars)
>> teslas = js_cars[0]
>> print(teslas)
{'manufacturer': 'Tesla Inc.', 'model': 'Tesla S', 'engineType': 'elecrical', 'horsePower': 362}

In this case, you got a JSON array containing two JSON objects.

You can only refer to a specific object in the JSON array using its index.

You can get the same data structure without using a JSON array, using only nested JSON objects. See here:

>> st_cars = '{"tesla s": {"manufacturer": "Tesla Inc.", "model": "Tesla S", "engineType": "elecrical", "horsePower": 362}, "tesla 3": {"manufacturer": "Tesla Inc.", "model": "Tesla 3", "engineType": "elecrical", "horsePower": 346}}' 
>> js_cars = json.loads (st_cars)
>> print(js_cars ["tesla 3"])
{'manufacturer': 'Tesla Inc.', 'model': 'Tesla 3', 'engineType': 'elecrical', 'horsePower': 346}

There’s just one JSON object with further JSON objects inside. The JSON objects contain two fields with the cars’ names, and the values are the corresponding JSON objects. 

If the wrapper is a JSON object instead of an array, then you can refer to the nested objects by their names, not by their numeric indexes.

JSON Objects vs. JSON Arrays: What Is the Difference?

Use of one method or another for transferring multiple objects in JSON is up to whatever it is you’re working with. It’s just a matter of taste. 

If it’s all up to you, you can choose however you want. Use nested JSON objects and refer to their fields by field name, or use JSON arrays and refer to their elements by index.

It’s worth noting that when you decode a JSON object that has a broken structure, you’ll get a JSONDecodeError

For example, if you forget to specify the name of the field manufacturer for one of the JSON array elements:

>> st_cars = '[{"Tesla Inc.", "model": "Tesla S", "engineType": "elecrical", "horsePower": 362}, {"manufacturer": "Tesla Inc.", "model": "Tesla 3 ","engineType": "elecrical"," horsePower": 346}]'  
>> js_cars = json.loads(st_cars)  
JSONDecodeError: Expecting ':' delimiter: line 1 column 15 (char 14)

Or if you put a number instead of a string in a field name:

>> st_cars = '[{123: "Tesla Inc.", "model": "Tesla S", "engineType": "elecrical", "horsePower": 362}, {"manufacturer": "Tesla Inc.", "model": "Tesla 3", "engineType": "elecrical", "horsePower": 346}]'  
>> js_cars = json.loads(st_cars)
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)

Also, if you try to create an array nested in a JSON object without specifying a field name:

>> st_cars = '{[{"manufacturer": "Tesla Inc.", "model": "Tesla S", "engineType": "elecrical", "horsePower": 362}, {"manufacturer": "Tesla Inc.", "model": "Tesla 3", "engineType": "elecrical", "horsePower": 346}]}'  
>> js_cars = json.loads(st_cars)
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Make sure you follow the JSON structure in your programs.

More Similar Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu