Markus
Markus

Reputation: 3782

How to put Array[Row] into JSON string

I have Array[Row] called arr (I obtained it after df.collect()) that I want to pass in my JSON string as key and value pairs:

val result = """{"field1": "A", "arr": [""" + arr + """]}"""

It should be:

{"field1": "A", "arr": [
       {"name":"Ford", "model": "Fiesta"},
       {"name":"Ford", "model": "Mustang"},
       ...
]}

If I do it the way that I showed above, it will not work.

Should I iterate over this array and manually define each parameter?:

arr.get(i).get(arr.get(i).fieldIndex("field1")).toString()

Upvotes: 1

Views: 106

Answers (1)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

You should be doing as below by using .toJSON as suggested by philantrovert in comments of the question

val result = """{"field1":"A","arr":"""+df.toJSON.collectAsList()+"""}"""

If you are using arr variable then you can do

val arr = df.toJSON.collectAsList()
val result = """{"field1":"A","arr":"""+arr+"""}"""

Upvotes: 1

Related Questions