Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Handling JSON Data in Python

DZone 's Guide to

Handling JSON Data in Python

Everything you need to get started with JSON in Python.

· Big Data Zone ·
Free Resource

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

Topics:
python ,json

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}