1

I have a Spark SQL query (using Scala as the language) which gives output as the following table where {name, type, category} is unique. Only type has limited values (due to 5-6 unique types).

name type category value
First type1 cat1 value1
First type1 cat2 value2
First type1 cat3 value3
First type2 cat1 value1
First type2 cat5 value4
Second type1 cat1 value5
Second type1 cat4 value5

I'm looking for a way to convert it into a JSON with Spark such that output is something like this, basically get the output for every name & type combination.

[
  {
    "name": "First",
    "type": "type1",
    "result": {
      "cat1": "value1",
      "cat2": "value2",
      "cat3": "value3"
    }
  },
  {
    "name": "First",
    "type": "type2",
    "result": {
      "cat1": "value1",
      "cat5": "value4"
    }
  },
  {
    "name": "Second",
    "type": "type1",
    "result": {
      "cat1": "value5",
      "cat4": "value5"
    }
  }
]

Is this possible via Spark scala? Any pointers or references would be really helpful. Eventually I have to write the JSON output to S3, so if this is possible during write then it will also be okay.

1
  • Does this answer your question? Spark Row to JSON Commented Aug 28, 2022 at 18:53

1 Answer 1

2

You can groupBy, collect_set then finally map_from_entries as below:

df = df
  .groupBy("name", "type")
  .agg(collect_set(struct("category", "value")).as("result"))
  .withColumn("result", map_from_entries(col("result")))

Exporting as JSON, however, will not give you the result as you expect. To get the expected result, you can use:

df.toJSON.collect.mkString("[", "," , "]" )

Final result:

[
  {
    "name": "First",
    "type": "type1",
    "result": {
      "cat3": "value3",
      "cat1": "value1",
      "cat2": "value2"
    }
  },
  {
    "name": "First",
    "type": "type2",
    "result": {
      "cat1": "value1",
      "cat5": "value4"
    }
  },
  {
    "name": "Second",
    "type": "type1",
    "result": {
      "cat1": "value5",
      "cat4": "value5"
    }
  }
]

Good luck!

Sign up to request clarification or add additional context in comments.

2 Comments

I'm curious, why wouldn't df.write.format("json").save("output.json") work?
Because Spark writes to JSON in a format that it can read (it can infer schema)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.