Interview Kickstart has enabled over 21000 engineers to uplevel.
JSON is a popular data format for interchange, and Python is a highly productive programming language with simple programming syntax. Hence, knowing how to work with JSON data in Python can be a useful tool in the arsenal of any software developer or coding engineer. Software engineers targeting Python programming jobs must especially learn how to work with JSON data in Python during their technical interview prep. In this article, we will learn:
JSON stands for JavaScript Object Notation as JSON’s syntax borrows from JavaScript’s object notation syntax. It is a lightweight data-interchange format used for representing, storing, and transferring structured data based on JavaScript object syntax. JSON exists as a string and stores JSON objects, which store data in the form of key-value pairs.
JSON object syntax:
Key-value pairs are separated by a comma (,) and each key and its corresponding value is separated by a colon. The keys themselves are strings, and values can be of one of the following data types: string, number, JSON object, Null, Boolean, or array. Arrays are enclosed in brackets ( [ , , ] ). A JSON object is written within braces ( { , , } ), and the value of a key itself can be a JSON object.
All this makes JSON an attractive choice for data interchange, and most modern languages support the generation and parsing of JSON format data. Let us now look at how JSON works in Python.
Python has a built-in package called json, through which the language supports working with the JSON data format. Hence, to work with JSON in Python, be it JSON strings or JSON files, we must import this json package. The json package has a json module, which contains functions for working with the JSON data format. Working with JSON involves making use of the methods in this json module.
In Python, JSON exists as a string, and JSON objects can be stored in a file.
Examples of JSON as a string:
Examples of JSON objects stored in a file:
The json module contains methods that help us read JSON files in Python. Let us look at the steps involved in the process:
The first step in reading a JSON file is importing the json package so that we can use methods like load() and loads() in its json module that will help us read the JSON file.
import json
The second step involves opening the JSON file, which we can do using the built-in function open(). The format for the open function is:
fileContent= open(“X:/filePath/fileName.json”)
Note the forward-slash (/) instead of backward slash (\) used in the path. We can also use a double backward slash (\\). The aim is for the path to read the whole path as a string and not treat something like \n in X:\filePath\newfile.json as an escape character. Here, the variable fileContent is of type string and will store the contents of the JSON file at the given path.
Next, we need to parse the JSON data stored in fileContent and store it as a Python dictionary. The load() function in the json module does exactly that and returns the JSON object as a python dictionary. So the returned dictionary stores the parsed data from the JSON file. The load function is written in the following format:
parsedJsonDictionary = json.load(fileContent)
When we use the load() or loads() function, we’re converting JSON objects into their corresponding Python objects. This process is called deserialization of JSON.
If we have JSON data in string format, we can use the loads() function, where the additional ‘s’ in loads() stands for the fact that it takes a JSON string as its argument.
parsedJsonDictionary = json.loads(data)
Since we’ve got what we need from the file, we should now close it. We do this using the close() function in the following format:
fileContent.close()
We have now successfully read the JSON file. Hence to read a JSON file, the steps involved are:
The JSON objects and their key-value pairs are all populated as a Python dictionary and can be accessed and printed the same way you would for any Python dictionary. We’ll now take an example where we read a file and show all these steps as they should occur in order.
# Python program for reading a JSON file
# Imports the JSON package
import json
# Opens the required JSON file
fileContent= open(“X:/filePath/fileName.json”)
# Returns a Python dictionary by deserializing JSON
parsedJsonDictionary = json.load(fileContent)
# Closing file
fileContent.close()
# Prints the Python dictionary that now stores the data in JSON file
print(parsedJsonDictionary)
Output:
The output is the contents of the JSON file fileName.json, stored as key-value pairs into a Python dictionary, just as any Python dictionary would be printed.
As we’ve learned, when JSON is deserialized, JSON objects are converted into their equivalent Python objects. Let us see what that looks like with the help of a table. The table states a JSON object and then states the Python object it’ll be stored as after deserialization using load()/loads():
For more tech interview questions and problems, check out the following pages: Interview Questions, Problems, Learn
Question 1: What’s the difference between a Python dictionary and a JSON object?
A Python dictionary is a data structure, while a JSON object is just a pure string written in a structured format. Strings in a Python dictionary use single quotes, whereas strings in a JSON object use double-quotes. There's also a difference in key — in a Python dictionary, a key can be any hash object; in a JSON object, a key has to be a string. Here’s a summary of the differences:
Question 2: What is the difference between load() and loads()?
The function loads() is used if the argument is a JSON string, while load() accepts a JSON file object as the argument. In other words, we use loads() to read JSON from a JSON string, use load() to read JSON from a JSON file object.
Question 3: What is the difference between a JSON object and a JSON string?
JSON always exists as a string. What we often refer to as JSON objects are JavaScript object literals. Data written in JSON format is only truly JSON if it’s used in a string context.
This is a JSON string:
data = ‘{“keyone”: “valueone”, “keytwo”: {“keyA”: “valueA”, keyB”: ”valueB”}}’
This is a JSON object, which is actually an object literal and not JSON:
dataObject = {“keyone”: “valueone”, “keytwo”: {“keyA”: “valueA”, keyB”: ”valueB”}}
Check out our learn page for articles on Python:
If you’re looking for guidance and help to nail your next technical interview, sign up for our free webinar.
As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land their dream jobs at Google, Facebook, Apple, Netflix, Amazon, and other Tier-1 tech companies.
Join our webinar to learn more!
----------
Article contributed Tanya Shrivastava
Attend our webinar on
"How to nail your next tech interview" and learn