GitHub user HyukjinKwon opened a pull request:

    https://github.com/apache/spark/pull/17192

    [SPARK-19849][SQL] Support ArrayType in to_json to produce JSON array

    ## What changes were proposed in this pull request?
    
    This PR proposes to support an array of struct type in `to_json` as below:
    
    ```scala
    import org.apache.spark.sql.functions._
    
    val df = Seq(Tuple1(Tuple1(1) :: Nil)).toDF("a")
    df.select(to_json($"a").as("json")).show()
    ```
    
    ```
    +----------+
    |      json|
    +----------+
    |[{"_1":1}]|
    +----------+
    ```
    
    Currently, it throws an exception as below (a newline manually inserted for 
readability):
    
    ```
    org.apache.spark.sql.AnalysisException: cannot resolve 
'structtojson(`array`)' due to data type 
    mismatch: structtojson requires that the expression is a struct 
expression.;;
    ```
    
    This allows the roundtrip with `from_json` as below:
    
    ```scala
    import org.apache.spark.sql.functions._
    import org.apache.spark.sql.types._
    
    val schema = ArrayType(StructType(StructField("a", IntegerType) :: Nil))
    val df = Seq("""[{"a":1}, 
{"a":2}]""").toDF("json").select(from_json($"json", schema).as("array"))
    df.show()
    
    // Read back.
    df.select(to_json($"array").as("json")).show()
    ```
    
    ```
    +----------+
    |     array|
    +----------+
    |[[1], [2]]|
    +----------+
    
    +-----------------+
    |             json|
    +-----------------+
    |[{"a":1},{"a":2}]|
    +-----------------+
    ```
    
    
    Also, this PR proposes to rename from `StructToJson` to 
`StructOrArrayToJson ` and `JsonToStruct` to `JsonToStructOrArray`.
    
    ## How was this patch tested?
    
    Unit tests in `JsonFunctionsSuite` and `JsonExpressionsSuite` for Scala, 
doctest for Python and test in `test_sparkSQL.R` for R.


You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/HyukjinKwon/spark SPARK-19849

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/spark/pull/17192.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #17192
    
----
commit 92922650ca6bf44ef4f4daf02653f66125e881d2
Author: hyukjinkwon <[email protected]>
Date:   2017-03-07T14:43:37Z

    Support ArrayType in to_json to produce JSON array

----


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to