Logo
  • Ubuntu
  • CentOS
  • Debian
  • Fedora
  • RedHat

Parsing JSON Data in Python - DesignLinux

designlinux 0 Comments

JSON is a human-readable text-based data format. It is language independent and used for data interchange between applications.

In this article, we’ll explain how to parse JSON data in Python.

Python JSON #

The json module that allows you to encode and decode JSON data is a part of the Python standard library.

JSON is a string that represents data. Encoding or serialization means transforming a Python object into a JSON string that can be stored in a file or transmitted over the network. Decoding or de-serialization the reverse process of encoding where a JSON string is transformed into Python object.

Below is a table showing Python objects and their equivalent JSON representation:

Python JSON
dict object
list, tuple array
str string
int, float number
True true
False false
None null

To work with JSON simply import the module at the top of your file:

import json

Encoding JSON in Python #

The json module has two methods for encoding Python objects into JSON formatted strings: dump() and dumps().

The dump() method sends the output to a file-like object. It takes two positional arguments: the object to be encoded and the file-like object. Here is an example:

data = {
    "country": "Germany",
    "vehicle": {
        "name": "Volkswagen",
        "model": "T-Roc"
    }
}

with open("file.json", "w") as file:
    json.dump(data, file)

If you run the script it will create a file named file.json:

file.json
{"country": "Germany", "vehicle": {"name": "Volkswagen", "model": "T-Roc"}}

The dumps() method works same as dump() but instead of sending the output to a file-like object, it returns a string:

data = {
    "country": "Germany",
    "vehicle": {
        "name": "Volkswagen",
        "model": "T-Roc"
    }
}

json.dumps(data)
'{"country": "Germany", "vehicle": {"name": "Volkswagen", "model": "T-Roc"}}'

Both methods accept same keyword arguments. For example if you are analyzing or debugging the JSON dat you may want to specify the indentation level:

data = {
    "country": "Germany",
    "vehicle": {
        "name": "Volkswagen",
        "model": "T-Roc"
    }
}

print(json.dumps(data, indent=2))
{
  "country": "Germany",
  "vehicle": {
    "name": "Volkswagen",
    "model": "T-Roc"
  }
}

Decoding JSON in Python #

To transform JSON encoded data into Python objects, use the load() and loads() methods.

The load() method reads JSON structure from a file-like object and transforms it into a Python object.

Let’s say we have the following JSON file:

file.json
[
  {
    "userId": 1,
    "id": 1,
    "title": "Meet with Lisa",
    "completed": true
  },
  {
    "userId": 1,
    "id": 2,
    "title": "Design a prototype",
    "completed": false
  }
]

To transform the JSON data to a Python representation, you would use something like this:

import json

with open('file.json') as f:
  data = json.load(f)

type(data)

The JSON is transformed into a Python list, that you can use in your code:

<class 'list'>

The loads() method converts a string containing a JSON document to a Python object:

import json

json_str= '{"userId": "1", "id": "1", "title": "Meet with Lisa", "completed": "True"}'

print(json.loads(json_str))

The string is transformed into a Python dictionary:

{'userId': '1', 'id': '1', 'title': 'Meet with Lisa', 'completed': 'True'}

Here is a more advanced example that shows how to make an api request and decode the JSON data:

import json
import requests

response = requests.get("https://jsonplaceholder.typicode.com/users")
users = json.loads(response.text)

print(users)

Conclusion #

We’ve hows you how to encode and decode JSON data in Python.

If you have any questions or feedback, feel free to leave a comment.

python

Related

Tags: python

How to Install WordPress with Nginx in Ubuntu 20.04

Prev Post

Ps Command in Linux (List Processes)

Next Post
Archives
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • July 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
Categories
  • AlmaLinux
  • Android
  • Ansible
  • Apache
  • Arch Linux
  • AWS
  • Backups
  • Bash Shell
  • Bodhi Linux
  • CentOS
  • CentOS Stream
  • Chef
  • Cloud Software
  • CMS
  • Commandline Tools
  • Control Panels
  • CouchDB
  • Data Recovery Tools
  • Databases
  • Debian
  • Deepin Linux
  • Desktops
  • Development Tools
  • Docker
  • Download Managers
  • Drupal
  • Editors
  • Elementary OS
  • Encryption Tools
  • Fedora
  • Firewalls
  • FreeBSD
  • FTP
  • GIMP
  • Git
  • Hadoop
  • HAProxy
  • Java
  • Jenkins
  • Joomla
  • Kali Linux
  • KDE
  • Kubernetes
  • KVM
  • Laravel
  • Let's Encrypt
  • LFCA
  • Linux Certifications
  • Linux Commands
  • Linux Desktop
  • Linux Distros
  • Linux IDE
  • Linux Mint
  • Linux Talks
  • Lubuntu
  • LXC
  • Mail Server
  • Manjaro
  • MariaDB
  • MongoDB
  • Monitoring Tools
  • MySQL
  • Network
  • Networking Commands
  • NFS
  • Nginx
  • Nodejs
  • NTP
  • Open Source
  • OpenSUSE
  • Oracle Linux
  • Package Managers
  • Pentoo
  • PHP
  • Podman
  • Postfix Mail Server
  • PostgreSQL
  • Python
  • Questions
  • RedHat
  • Redis Server
  • Rocky Linux
  • Security
  • Shell Scripting
  • SQLite
  • SSH
  • Storage
  • Suse
  • Terminals
  • Text Editors
  • Top Tools
  • Torrent Clients
  • Tutorial
  • Ubuntu
  • Udemy Courses
  • Uncategorized
  • VirtualBox
  • Virtualization
  • VMware
  • VPN
  • VSCode Editor
  • Web Browsers
  • Web Design
  • Web Hosting
  • Web Servers
  • Webmin
  • Windows
  • Windows Subsystem
  • WordPress
  • Zabbix
  • Zentyal
  • Zorin OS
Visits
  • 1
  • 420
  • 551,895

DesignLinux.com © All rights reserved

Go to mobile version