1

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()
2
  • Why don't you use to_json (with Dataframes) or toJSON with RDDs? What does the result of df.collect() look like ? Commented Feb 9, 2018 at 14:20
  • @philantrovert: If I do df.toJSON, then it returns Dataset[String]. What do I do with it? Commented Feb 9, 2018 at 15:02

1 Answer 1

1

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+"""}"""
Sign up to request clarification or add additional context in comments.

Comments

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.