Convert Python Dictionary Object to JSON String

Last updated on Mar 05, 2024
Definition: dictToJsonString(dictionary: dict) → str
Description: Converts a Python dictionary object into a JSON string
Parameters: jsonString: The dictionary object which needs to be converted
Returns: A JSON-formatted string created from the input dictionary

The following script converts an object, <dictionary>, into a JSON-formatted string using the dictToJsonString function. The resulting dictionary is assigned to the <jsonDict> field.

Note: Replace the placeholder values in the script with your own values.

from io.hevo.api import Event
from io.hevo.api import Utils

def transform(event):
    eventName = event.getEventName()
    properties = event.getProperties()

    <dictionary> = {<"key-value1": "key-value2", "key-value3": "key-value4">} # JsonObject from a source table
    properties['jsonStr'] = Utils.dictToJsonString(<dictionary>)
    return event

Sample Transformation

Consider an object, Billing with the following fields:

  • name- Eric
  • location - USA
  • exp - 15years

The dictToJsonString function extracts the customer details (name, location, and exp) from the Billing object and converts these in a JSON-formatted string. This JSON string is then assigned to the customer field under properties.

from io.hevo.api import Event
from io.hevo.api import Utils

def transform(event):
    eventName = event.getEventName()
    properties = event.getProperties()

    customer_keys = ['name', 'location', 'exp']

    customer = {}
    for key in customer_keys:
        customer[key] = properties[key]
        del properties[key]

    customer_str = Utils.dictToJsonString(customer)
    properties['customer'] = customer_str

    return event

Sample Output

The name, location, and exp fields and their values are displayed in the customer field as a JSON string.

Sample Output - Convert Python Dictionary Object to JSON String



Revision History

Refer to the following table for the list of key updates made to this page:

Date Release Description of Change
Jun-26-2023 NA New document.

Tell us what went wrong