2
+------------------------------------------------------------------+
| message                                                          |
+------------------------------------------------------------------+
|{"name":"east-desktop","viewers":447,"emptyCount":0,"version":0.3}|
|{"name":"west-desktop","viewers":111,"emptyCount":0,"version":0.6}|
|{"name":"west-desktop","viewers":115,"emptyCount":0,"version":0.1}|
+------------------------------------------------------------------+

message:string

I have a dataframe which contains json data within one column, I would like to extract the data in to either separate columns or as json file.

I am working within a Databricks notebook using pyspark.

Dataframe

+---------------------------------------------+
| name        | viewers| emptyCount | version |
+---------------------------------------------+
|east-desktop | 447    | 0          | 0.3     |
|west-desktop | 111    | 0          | 0.6     |
|west-desktop | 115    | 0          | 0.1     |
+---------------------------------------------+

OR Json

{
  "name": "east-desktop",
  "viewers":  447,
  "emptyCount": 0,
  "version": 0.3,
}
0

1 Answer 1

3

pault was right it is pretty much the same question, but you can use the following sample to achieve your dataframe output:

df_new = spark.createDataFrame([
(str({"name":"east-desktop","viewers":447,"emptyCount":0,"version":0.3}))
],StringType())

schema = StructType(
    [
        StructField('name', StringType(), True),
        StructField('viewers', IntegerType(), True),
        StructField('emptyCount', IntegerType(), True),
        StructField('version', FloatType(), True)
   ]
)
df_new.withColumn("data", from_json("value",schema)).select("value", col('data.*')).show(truncate=False)

Output:

+-------------------------------------------------------------------------+------------+-------+----------+-------+
|value                                                                    |name        |viewers|emptyCount|version|
+-------------------------------------------------------------------------+------------+-------+----------+-------+
|{'emptyCount': 0, 'version': 0.3, 'name': 'east-desktop', 'viewers': 447}|east-desktop|447    |0         |0.3    |
+-------------------------------------------------------------------------+------------+-------+----------+-------+
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.