I am working with pyspark. I have a spark data frame which is of the following format
| person_id | person_attributes
____________________________________________________________________________
| id_1 "department=Sales__title=Sales_executive__level=junior"
| id_2 "department=Engineering__title=Software Engineer__level=entry-level"
I have written a python function which takes the person_id and person_attributes and returns a json of the following format
{"id_1":{"properties":[{"department":'Sales'},{"title":'Sales_executive'},{}]}}
But I don't how to register this as a udf in pyspark with proper output type. Here is the python code
def create_json_from_string(pid,attribute_string):
results = []
attribute_map ={}
output = {}
# Split the attribute_string into key,value pair and store it in attribute map
if attribute_string != '':
attribute_string = attribute_string.split("__") # This will be a list
for substring in attribute_string:
k,v = substring.split("=")
attribute_map[str(k)] = str(v)
for k,v in attribute_map.items():
temp = {k:v}
results.append(temp)
output ={pid : {"properties": results }}
return(output)