Share

Splitting JSON Objects into ArrayLists

In this example, we will split JSON objects from a JSON data string into ArrayLists.

Consider the following sample Event from the FIFA Event Type, which contains the details of five venues in the locations object:

{
	"event_name": "FIFA",
	"properties": {
		"locations" : "{\"Venue 1\": {\"id\": 3445, \"name\":\"Doha\"}, \"Venue 2\": {\"id\": 6061, \"name\":\"Lusail\"}, \"Venue 3\": {\"id\": 6062, \"name\":\"Al Khor\"}, \"Venue 4\": {\"id\": 6063, \"name\":\"Al Rayyan\"}, \"Venue 5\": {\"id\": 6064, \"name\":\"Al Wakrah\"}}"
	}
}		

The following Transformation script:

  • Creates ArrayLists from the id and name keys in the locations object.

  • Adds the values of the id and name keys as the elements to the corresponding ArrayList.

from io.hevo.api import Event

import json

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

    if 'locations' in properties:
        for k,v in json.loads(properties["locations"]).items():
            for key, value in v.items():
                properties["locations."+key] =[]

        for k,v in json.loads(properties["locations"]).items():
            for key, value in v.items():
                properties["locations."+key].append(value)

        for each in range(len(properties["locations.id"])):
            properties["locations.id"][each]=int(properties["locations.id"][each])

        del properties["locations"]
    return event

The output from the above snippet is:

{
	"event_name": "FIFA",
	"properties": {
		"locations.name": "[\"Al Wakrah\",\"Lusail\",\"Al Rayyan\",\"Al Khor\",\"Doha\"]",
		"locations.id": "[6064,6061,6063,6062,3445]"
	}
}

As you can see above, the Transformation splits the locations object into the locations.name and locations.id ArrayLists.

Last updated on May 30, 2023

Tell us what went wrong

Skip to the section