How to Encode Data From Python To JSON

Objective

Encode Python data into JSON.

Distributions

This will work on any distribution with Python installed.

Requirements

A working Linux install with Python

Difficulty

Easy

Conventions

  • # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
  • $ – requires given linux commands to be executed as a regular non-privileged user

Introduction

JSON is the universal format for passing data between programs and/or languages, especially on the web. Python has excellent built-in support for converting data from a Python program into JSON for another program to use.

Basic Encoding

Python’s JSON support comes from a module. Before you can work with JSON, you need to import it.

import json

Next, the method requires that your data be arranged in a dictionary. Set up a dictionary to work with.

distro_install_command = {'Debian': 'apt', 
						  'Ubuntu': 'apt',
						  'Fedora': 'dnf', 
						  'CentOS': 'yum',
						  'OpenSUSE': 'zypper',
						  'Arch': 'pacman',
						  'Gentoo': 'emerge'
}

There is a method called dumps in the json module that you can use to “dump” your data into JSON.

distro_json = json.dumps(distro_install_command)

Try printing it out.

print(distro_json)

It’s somewhat neat, since it was already a dictionary, but it’s not presented in the usual JSON structure.

Sorting

If you want your JSON to print out like JSON, there are a couple of extra options that you need to pass to json.dumps.

distro_json = json.dumps(distro_install_command, sort_keys=True, indent=4)

Try printing that out. It’ll look more like you’d expect.

print(distro_json)

File Output

It’s probably better to output that JSON to somewhere that it can be accessed. The most common option on the web is to create an API with JSON. That’s a little out of the scope of this guide, so it’ll cover creating a file instead.

So, this part is easier to work with out of a Python file, since you have to lay out all of the pieces. Set up a file with the import and the dictionary from above on top.

Now, the easiest structure to use for this is the with statement. It condenses a lot of code into a simplified form and ensures that your file closes. Your with statement should look like the one below.

with open('distros.json', 'w') as f:
    json.dump(distro_install_command, f)

The JSON will be written to the file after that block runs. Notice the subtle differences. This requires the dump method instead of the dumps method. dumps treats it as a string, and that can mess things up.

Objects

You can serialize objects into JSON too, but it requires a bit of extra work. json.dumps only accepts dictionaries, so you’ll need to use the __dict)) attribute of the object. It contains the information about the object organized in a dictionary, and can be used to treat the object like it is a dictionary.

Create an object to work with.

class Test(object):
    def __init__():
	    self.a = 10
		self.b = 15
		self.c = 20

test1 = Test()

You can pass the object that you instantiated to json.dumps.

print(json.dumps(test1.__dict__))

You’ll see the variables that you set in the object printed out.

Closing Thoughts

That’s it for encoding JSON. You can definitely do more, and play around different data configurations. JSON and dictionaries have similar syntax and structure, so it’s easy to arrange your data in an simple to understand way.

Exercises

  1. Import the JSON module
  2. Create a dictionary to encode
  3. Print the encoded dictionary
  4. Print the dictionary encoded and sorted
  5. Export your dictionary as JSON to a file
  6. Create a Python object containing instance data
  7. Print your object as JSON
  8. Export your object as JSON to a file


Comments and Discussions
Linux Forum