Home > Python for ENCOR

Python for ENCOR

The ENCOR exam requires you to have some basic knowledge of Python for processing file, sending REST API and proceeding the response so we write this tutorial to help you grasp them.

First understand the dictionary type in Python. One of two ways to create the dictionary type is using a set of curly braces, {} like this:

# This creates a Python object (dictionary type):
data = {
"name": "John",
"age": 25
}

We will use this type regularly in below examples.

Working with json package (import json)

The json.dumps() function is used to convert Python objects (dictionary, list, string, integer, boolean… type) into JSON strings. The name of the function means dump the data as a string, note that the final “s” in “dumps” stands for “string”. Here’s a simple example:

import json
data = {'name': 'John', 'age': 25} #Define a Python dictionary
json_data = json.dumps(data) #Use json.dumps() to convert the dictionary into a JSON string
print(json_data) #Output: '{"name": "John", "age": 25}'

The json.loads() converts a JSON string into a Python dictionary type so it is opposite to json.dumps() so we can append these codes to above example:

dict = json.loads(json_data)
print(dict) #Output: {'name': 'John', 'age': 25}
print(type(dict)) #Output: <class 'dict'>
In short, the json.loads() converts a JSON string into a Python dictionary type while json.dumps() takes in a JSON object (dictionary type or other types) and returns a string.

More about json.dumps()

The json.dumps() method is very powerful in handling more complex structures. It can handle lists, nested dictionaries, and other complex Python objects easily. Another example of using json.dumps for complex Python object is shown below:

import json
# Define a complex Python object
data = {
  'name': 'John',
  'age': 25,
  'pets': ['Dog', 'Cat'],
  'profile': {
    'job': 'Engineer',
    'city': 'New York'
  }
}
# Use json.dumps() to convert the object into a JSON string
json_data = json.dumps(data)
print(json_data)
# Output:
# '{"name": "John", "age": 25, "pets": ["Dog", "Cat"], "profile": {"job": "Engineer", "city": "New York"}}'

Work with a JSON file (read & write file, convert to JSON string or Python object)

There are some ways to proceed a JSON file in Python:

Read a JSON file

1. The short way:

We can use “file.load()” method (notice: “load”, not “loads”) to read a file object and parse it at the same time:

with open("user.json", "r") as json_file: 
    json_file_content = json_file.load(json_file)

print(json_file_content)
# {
# 'name': 'John',
# 'age': 25
# }

2. The long way:

We read the file first then parse it later with json.loads() function.

with open('user.json') as json_file:
    file_contents = json_file.read()

parsed_json = json.loads(file_contents)
print(parsed_json)
# {
# 'name': 'John',
# 'age': 25
# }

Write to a JSON file

The json.dump() function is similar to json.dumps(), but instead of converting the Python object to a JSON string, it writes the JSON data directly to a file.

import json
# Define a Python dictionary
data = {'name': 'John', 'age': 30}
# Use json.dump() to write the dictionary into a JSON file
with open('data.json', 'w') as f:
    json.dump(data, f)
# Verify the contents of the file
with open('data.json', 'r') as f:
    print(f.read())
# Output:
# '{"name": "John", "age": 30}'

Quick summary

Method Usage
json.loads() Take a JSON string and convert to a Python dictionary
json.load() Read a JSON file and parse it into a dictionary directly
json.dumps() Take any object and returns a JSON string
json.dump() Take any object and write directly to a file

In the next tutorial we will find out how to send request and receive response with REST API in Python.

Comments
  1. SALIM
    December 6th, 2023

    HI
    Last part of this quote is wrong:
    “In short, the json.loads() converts a JSON string into a Python dictionary type while json.dumps() takes in a JSON object (dictionary type) and returns a string.”

    json.dumps() takes in a Python object (dictionary or other types) and return a string in JSON format.

  2. digitaltut
    December 6th, 2023

    @SALIM: Thank you for your detection, we updated it!

  3. tech-learner
    November 3rd, 2024

    There is a statement in the end “In the next tutorial we will find out how to send request and receive response with REST API in Python.” I’m unable to find the link to the next tutorial.

  1. No trackbacks yet.