简体   繁体   中英

PySpark - rename key names in JSON stored as string column in CSV file

I want to update key name in my json stored as string column and save it back as string type column. I am reading such columns from my csv & storing back as csv.

This is how my input csv looks.

candidate_email,transactions
cust2@email.com,"[{'transaction_id':'12', 'transaction_amount':'$23.43'},{'transaction_id':'15', 'transaction_amount':'$723.41'}]"
cust1@email.com,"[{'transaction_id':'10', 'transaction_amount':'$55.99'},{'transaction_id':'11', 'transaction_amount':'$20.46'},{'transaction_id':'13', 'transaction_amount':'$5.89'},{'transaction_id':'14', 'transaction_amount':'$35.61'}]"

I want to replace transaction_id key with id and transaction_amount with amount in my json and save it back as csv.

input_df = spark.read.csv('transactions/*.csv', header='true', inferSchema = True)
input_df.printSchema()
# root
#  |-- candidate_email: string (nullable = true)
#  |-- transactions: string (nullable = true)

input_df.show(10, False)
# +-----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
# |candidate_email|transactions                                                                                                                                                                                                                |
# +-----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
# |cust2@email.com        |[{'transaction_id':'12', 'transaction_amount':'$23.43'},{'transaction_id':'15', 'transaction_amount':'$723.41'}]                                                                                                            |
# |cust1@email.com        |[{'transaction_id':'10', 'transaction_amount':'$55.99'},{'transaction_id':'11', 'transaction_amount':'$20.46'},{'transaction_id':'13', 'transaction_amount':'$5.89'},{'transaction_id':'14', 'transaction_amount':'$35.61'}]|
# +-----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

How can I replace my keys to get following output?

output_df.show(10,False)
# +---------------+----------------------------------------------------------------------------------------------------------------------------+
# |candidate_email|transactions                                                                                                                |
# +---------------+----------------------------------------------------------------------------------------------------------------------------+
# |cust1@email.com|[{'id':'10', 'amount':'$55.99'},{'id':'11', 'amount':'$20.46'},{'id':'13', 'amount':'$5.89'},{'id':'14', 'amount':'$35.61'}]|
# |cust2@email.com|[{'id':'12', 'amount':'$23.43'},{'id':'15', 'amount':'$723.41'}]                                                            |
# +---------------+----------------------------------------------------------------------------------------------------------------------------+

Note: both columns are string type columns.

output_df.printSchema()
# root
#  |-- candidate_email: string (nullable = true)
#  |-- transactions: string (nullable = true)

Use from_json to read transactions column as array(struct...) then cast to the required field names.

  • then explode + to_json + groupBy + collect_list to get required json.

Example:

df.show()
#+---------------+----------------------------------------------------------------------------------------------------------------+
#|candidate_email|transactions                                                                                                    |
#+---------------+----------------------------------------------------------------------------------------------------------------+
#|cust2@email.com|[{'transaction_id':'12', 'transaction_amount':'$23.43'},{'transaction_id':'15', 'transaction_amount':'$723.41'}]|
#+---------------+----------------------------------------------------------------------------------------------------------------+

st=ArrayType(StructType([StructField("transaction_id", StringType()),StructField("transaction_amount", StringType())]))

df.withColumn("jsn",from_json(col("transactions"),st).cast("array<struct<id:string,amount:string>>")).\
selectExpr("*","explode(jsn)").\
select("*","col.*").\
drop(*drop_cols).\
selectExpr("candidate_email","to_json(struct(id,amount)) as trans").\
groupBy("candidate_email").\
agg(collect_list("trans").alias("transactions")).\
show(10,False)

#+---------------+---------------------------------------------------------------+
#|candidate_email|transactions                                                   |
#+---------------+---------------------------------------------------------------+
#|cust2@email.com|[{"id":"12","amount":"$23.43"}, {"id":"15","amount":"$723.41"}]|
#+---------------+---------------------------------------------------------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM