Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ private[sql] class JSONOptions(
}
val lineSeparatorInWrite: String = lineSeparator.getOrElse("\n")

/**
* Generating JSON strings in pretty representation if the parameter enabled.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"if the parameter enabled" => "if the parameter is enabled"

*/
val pretty: Boolean = parameters.get("pretty").map(_.toBoolean).getOrElse(false)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm .. so now finally this became an actual problem. This is specifically for JSON functions and documented nowhere. Can we deal with this problem?


/** Sets config options on a Jackson [[JsonFactory]]. */
def setJacksonOptions(factory: JsonFactory): Unit = {
factory.configure(JsonParser.Feature.ALLOW_COMMENTS, allowComments)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ private[sql] class JacksonGenerator(
s"Initial type ${dataType.catalogString} must be a ${MapType.simpleString}")
}

private val gen = new JsonFactory().createGenerator(writer).setRootValueSeparator(null)
private val gen = {
val generator = new JsonFactory().createGenerator(writer).setRootValueSeparator(null)
if (options.pretty) generator.useDefaultPrettyPrinter() else generator
}

private val lineSeparator: String = options.lineSeparatorInWrite

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -518,4 +518,25 @@ class JsonFunctionsSuite extends QueryTest with SharedSQLContext {
jsonDF.select(to_json(from_json($"a", schema))),
Seq(Row(json)))
}

test("pretty print - roundtrip from_json -> to_json") {
val json = """[{"book":{"publisher":[{"country":"NL","year":[1981,1986,1999]}]}}]"""
val jsonDF = Seq(json).toDF("root")
val expected =
"""[ {
| "book" : {
| "publisher" : [ {
| "country" : "NL",
| "year" : [ 1981, 1986, 1999 ]
| } ]
| }
|} ]""".stripMargin

checkAnswer(
jsonDF.select(
to_json(
from_json($"root", schema_of_json(lit(json))),
Map("pretty" -> "true"))),
Seq(Row(expected)))
}
}