DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • What Is Pydantic?
  • Reversing an Array: An Exploration of Array Manipulation
  • Best Python Libraries for Web Scraping
  • Using A/B Testing To Make Data-Driven Product Decisions

Trending

  • Agile Estimation: Techniques and Tips for Success
  • Monkey-Patching in Java
  • REST vs. Message Brokers: Choosing the Right Communication
  • Software Verification and Validation With Simple Examples
  1. DZone
  2. Coding
  3. Languages
  4. Handling JSON Data in Python

Handling JSON Data in Python

Everything you need to get started with JSON in Python.

Bipin Patwardhan user avatar by
Bipin Patwardhan
·
Oct. 09, 19 · Tutorial
Like (5)
Save
Tweet
Share
10.37K Views

Join the DZone community and get the full member experience.

Join For Free

key-in-fall-leaves


I recently finished writing two assets — a Spark-based data ingestion framework and a Spark-based data quality framework; both were metadata-driven. As is typical, the behavior of the assets is stored in an RDBMS. In the data ingestion framework, I needed to store parameters for the source (information like username, password, path, format, etc), the destination (information like username, password, path, format, etc), compression, etc. In normal schemas, I have seen these parameters modeled as columns in a table.

Being a programmer at heart, I decided not to use multiple columns. Instead, all the parameters would be stored in a single column (as a string in the database table). The Spark application would have the responsibility of reading the string and extracting the required parameters.

After making that (seemingly simple) decision, the next step was to define the format of the "parameter" string. For this purpose, I chose JSON without hesitation. Though parsing a CSV-like format would have been easy, JSON offers a lot of flexibility — but at some cost.

After spending some time exploring various options of JSON parsing in Spark, I developed a Scala class for this purpose, using the Scala Parsing library. In the programming world, there is more than one way to do one task; even for JSON parsing, many libraries are available, namely Json4s, Play JSON, Spray JSON, etc. I will post details of the Scala exploration in a subsequent article.

After working on parsing JSON using Scala, I wanted to try something similar in Python. I found that JSON parsing is trivial in Python (essentially just one import and one line of code).

import json

str1 = '{ "name": "John Smith", "city": "New York", "id": 123, "numbers": [1, 2, 3, 4], "address": { "house": "43", "street": "privet drive" } }'
map = json.loads(str1)
print(map["name"], map["city"], map["address"])


As we have the habit of making simple things complicated, I decided to live up to the expectation by encapsulating the JSON parsing logic inside a class, named CustomJSON.

import json

class CustomMap:
  def __init__(self):
    self.pmap = dict()

  def createFromJSON(self, jsonData):
    self.pmap = json.loads(jsonData)

  def createFromDict(self, data):
    self.pmap = data

  def getString(self, field, defVal=""):
    retVal = defVal
    try:
      retVal = str(self.pmap[field])
    except KeyError:
      retVal = defVal
    return retVal

  def getInt(self, field, defVal=0):
    retVal = defVal
    try:
      retVal = int(self.pmap[field])
    except KeyError:
      retVal = defVal
    return retVal

  def getFloat(self, field, defVal=0.0):
    retVal = defVal
    try:
      retVal = int(self.pmap[field])
    except KeyError:
      retVal = defVal
    return retVal

  def getList(self, field, defVal=[]):
    retVal = defVal
    try:
      retVal = self.pmap[field]
    except KeyError:
      retVal = defVal
    return retVal

  def getObject(self, field, defVal=None):
    retVal = defVal
    try:
      retVal = self.pmap[field]
    except KeyError:
      retVal = defVal
    return retVal

  def getObjectAsCustomMap(self, field, defVal=None):
    retVal = defVal
    try:
      val = self.pmap[field]
      print(val)
      ncm = CustomMap()
      if val != None:
        print("val is not null")
        ncm.createFromDict(val)
        retVal = ncm
    except KeyError:
      retVal = defVal
    return retVal
#end CustomMap

str1 = '{ "name": "John Smith", "city": "New York", "id": 123, "numbers": [1, 2, 3, 4], "address": { "house": "43", "street": "privet drive" } }'

cm = CustomMap()
cm.createFromJSON(str1)
print(cm.getString("name", "xxx"))
print(cm.getInt("id", 42))
print(cm.getInt("id123", 42))
print(cm.getList("numbers"))
print(cm.getList("numbers")[0])
print(cm.getObject("address"))
print(type(cm.getObject("address")))
ncm = cm.getObjectAsCustomMap("address", None)
print(ncm.getString("house"))


While you may scoff at the class, the key benefit of the class (as per me) is that KeyError exception is handled by the class, making JSON parsing simpler and cleaner in the application. The application no longer needs to worry about the exception.


Further Reading

  • Exporting Data From PDFs With Python.
  • How to Use Python With Real-Time Data and REST APIs.
  • Boto3: Amazon S3 as Python Object Store.
JSON Python (language) Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • What Is Pydantic?
  • Reversing an Array: An Exploration of Array Manipulation
  • Best Python Libraries for Web Scraping
  • Using A/B Testing To Make Data-Driven Product Decisions

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: