Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a json object in to a json array using scala play?

In my scala code i have a json object consisting email data

val messages = inboxEmail.getMessages();
var jsonArray = new JsArray
for(inboxMessage <- messages)
{
    ...
    ...
    val emailJson = Json.obj("fromAddress" -> fromAddressJsonList, "toAddress" -> toAddressJsonList, "ccAddress" -> ccAddressJsonList, "bccAddress" -> bccAddressJsonList, "subject" -> emailMessage.getSubject().toString(), "message" -> Json.toJson(emailMessageBody))

I need to add emailJson to the jsonArray during each loop

i tried

jsonArray.+:(emailJson)

and

jsonArray.append(emailJson)

but getting empty array

What should i use here to add jsonObject into the json array

like image 278
James Avatar asked May 20 '14 07:05

James


People also ask

How do I add an object to a JSON file?

You need to load the file, then parse it using var val = JSON. parse(textFromFile) you can then use push to push it onto the end of that val val. push({/*new object*/}) , then you will need to stringify the val var newString = JSON. strigify(val) and then you finally can save newString to a file.

What is a JSValue?

You use the JSValue class to convert basic values, such as numbers and strings, between JavaScript and Objective-C or Swift representations to pass data between native code and JavaScript code.

What is the best json library for Scala?

Argonaut is a great library. It's by far the best JSON library for Scala, and the best JSON library on the JVM. If you're doing anything with JSON in Scala, you should be using Argonaut. circe is a fork of Argonaut with a few important differences.


1 Answers

Remember that JsArray is immutable, so writing

jsonArray.+:(emailJson)

will not modify jsonArray, it will just create a new json array with emailJson appended at the end.

Instead you would need to write something like:

val newArray = jsonArray +: emailJson

and use newArray instead of jsonArray afterwards.

In your case, you said you need to add an element "at each loop iteration". When using a functional language like Scala, you should probably try to think more in terms of "mapping over collections" rather than "iterating in a loop". For example you could write:

val values = messages map {inboxMessage =>
    ...
    ...
    Json.obj("fromAddress" -> fromAddressJsonList, "toAddress" -> toAddressJsonList, "ccAddress" -> ccAddressJsonList, "bccAddress" -> bccAddressJsonList, "subject" -> emailMessage.getSubject().toString(), "message" -> Json.toJson(emailMessageBody))
}
val newArray = objects ++ JsArray(values)
like image 185
noziar Avatar answered Sep 24 '22 02:09

noziar