Converting a Map to Json in Play Scala: A Step-by-Step Guide

Is there a way to convert the given Map structure, which is of type Map[String,Any], into JSON in Scala using Play framework?


val result =  s
  .groupBy(_.dashboardId)
  .map(
    each => Map(
      "dashboardId" -> each._1,
      "cubeId" -> each._2.head.cubeid,
      "dashboardName" -> each._2.head.dashboardName,
      "reports" -> each._2.groupBy(_.reportId).map(
        reportEach => Map(
          "reportId" -> reportEach._1,
          "reportName" -> reportEach._2.head.reportName,
          "selectedColumns" -> reportEach._2.groupBy(_.selectedColumnid).map(
            selectedColumnsEach => Map(
              "selectedColumnId" -> selectedColumnsEach._1,
              "columnName" -> 
              selectedColumnsEach._2.head.selectColumnName.orNull,
              "seq" ->selectedColumnsEach._2.head.selectedColumnSeq,
              "formatting" -> selectedColumnsEach._2
                )
             )
           )
         )
     )
 

Answer ā„–1

It is not possible to directly convert a Map[String, Any] to Json, however, you can convert a Map[String, String] or Map[String, JsValue].

To achieve this in your scenario, you can first convert each map value to a JsValue using the following approach:

Map(
  "dashboardId" -> Json.toJson(each._1),
  "cubeId" -> Json.toJson(each._2.head.cubeid),
  "dashboardName" -> Json.toJson(each._2.head.dashboardName),
  "reports" -> Json.toJson(each._2.groupBy(_.reportId).map(
    reportEach => Map(
      "reportId" -> Json.toJson(reportEach._1),
      "reportName" -> (reportEach._2.find(_.reportName != null) match {
        case Some(reportNameData) -> Json.toJson(reportNameData.reportName)
        case None -> JsNull
      })),
  ...
)

Answer ā„–2

After reading the results into a Seq[Map[String,Any]] using .toSeq, I successfully converted it into Json with the help of toJson function.

val s = new SaveTemplate getReportsWithDashboardId(dashboardId)
val result : Seq[Map[String,Any]] =  s.groupBy(_.dashboardId)
  .map(
    each => Map(
      "dashboardId" -> each._1,
      "cubeId" -> each._2.head.cubeid,
      "dashboardName" -> each._2.head.dashboardName,
      "reports" -> each._2.groupBy(_.reportId).map(
        reportEach => Map(
          "reportId" -> reportEach._1,
          "reportName" -> (reportEach._2.find(_.reportName != null) match {
          case Some(reportNameData) => reportNameData.reportName
          case None => null
        }),
          "selectedColumns" -> reportEach._2.groupBy(_.selectedColumnid).map(
            selectedColumnsEach => Map(
              "selectedColumnId" -> selectedColumnsEach._1,
              "columnName" -> selectedColumnsEach._2.head.selectColumnName.orNull,
              "seq" ->selectedColumnsEach._2.head.selectedColumnSeq,
              "formatting" -> Map(
              "formatId" -> (selectedColumnsEach._2.find(_.formatId != null) match {
                case Some(reportNameData) => reportNameData.formatId
                case None => null
              }),
              "formattingId" -> (selectedColumnsEach._2.find(_.formattingid != null) 
              match {
                case Some(reportNameData) => reportNameData.formattingid
                case None => null
              }),
              "type" -> (selectedColumnsEach._2.find(_.formattingType != null) match 
              {
                case Some(reportNameData) => reportNameData.formattingType
                case None => null
              })
            )
           )
          )
        )
      )
    )
  ).toSeq
val k = toJson(result)
Ok(k)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble displaying JSON response in Firefox console with Django

Code Snippet: from .views import get_data app_name = 'javascript' urlpatterns = [ path('', views.index, name='index'), path('api/data', get_data, name='api-data'), ] Views.py: from django.http ...

Flask response fails to retain non-visible characters in string

My Python string variable has a unique format: '\x1d0103671286378126378127812\x1d1232321102I009B\x1d71012321271' When I send it in a json response, the \x1d characters disappear. Strangely enough, when I print it on the con ...

How can I prevent writeFileSync from replacing existing data?

When I use this line of code, it deletes all existing data. Is there a method or function that will append the new data on a new line instead? fs.writeFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey)); ...

Unable to retrieve a specific property from a JSON object that was returned

After receiving a response from an ajax request, I save the request.responseText in a variable called requestData. The data in requestData consists of a JSON object passed by PHP using json_encode(). Take a look at some log entries below. requestData : { ...

Angular directive dilemma

Angular is causing some issues for me as I am a beginner in using it. Below is the JSON data that I am dealing with: [ { "name":"43", "values":{ "audio":"Audio Only", "low":"Low Bandwidth", "medium":"Medium Bandw ...

Difficulty encountered while deserializing a particular Json object within a C# desktop application

I am currently facing an issue with deserializing the following JSON data. This JSON is retrieved from a server and needs to be used in a desktop application. { "panicForms": [{ "name": "Name", "description": ...

Navigating through objects within arrays within objects in Angular

I seem to be encountering some difficulty in displaying data from an API call on Mapbox. Only one marker is showing up on the map instead of the expected 10 markers. I suspect there might be an issue with my ng-repeat implementation, but I can't pinpo ...

Kotlin does not interpret 'is' as the beginning of a JSON key

I have encountered a peculiar problem recently. I am working with a data class that is used for parsing Json. Within this data class, there is an attribute: val isExpired: Boolean However, after creating the response, it seems that instead of using isE ...

Ways to verify if a variable holds a JSON object or a string

Is it possible to determine whether the data in a variable is a string or a JSON object? var json_string = '{ "key": 1, "key2": "2" }'; var json_string = { "key": 1, "key2": "2" }; var json_string = "{ 'key': 1, 'key2', 2 } ...

Attempting to transform a JSON file or string into a CSV format results in an unpopulated CSV file

So I have this task of converting a JSON file to a CSV file. I'm using the Google Sheets API to export the JSON file, but when I try to convert it, either with the file location or as a string, I always get a null pointer exception or an empty CSV fil ...

Why isn't my PHP code adding information to my MySQL database?

https://i.stack.imgur.com/a1eNG.jpgThe purpose of this script is to input data into a mysql database and generate JSON code for use in an Android application. However, during testing, the following result was obtained: Json Result after Testing On PostMan ...

Creating JSON data in PHP is a straightforward process that involves encoding

I am looking to generate a JSON output that looks like this: { "id": "c200", "name": "Aneesh", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e7e8c6e1ebe7efeaa8e5e9eb">[email protected]</a> ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, Iā€™m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

Encountering a JSONDecodeError with the message "Expecting value: line 1 column 1 (char 0), I have come across this

Looking for a solution to the JSONDecodeError: Expecting value: line 1 column 1 (char 0) error? Check out the code snippet provided below: from urllib.request import urlopen api_url = "https://samples.openweathermap.org/data/2.5/weatherq=Lon ...

Update the input type from string to data in MONGO DB format

Is there a way to efficiently convert the inspection_date field in my database from string to date for all objects, similar to the structure below? {"name": "$1 STORE", "address": "5573 ROSEMEAD BLVD", "city": "TEMPLE CITY", "zipcode": "91780", "state": "C ...

How to extract and display data in Python using JSON parsing techniques

In search of the right syntax for extracting and displaying specific JSON data using Python Check out this example JSON file: Sample JSON Response from Play Information: { "id": 111, "age": 22, "Hobby": [ { "List": 1, "Sev": "medium", "name": "play 1" ...

Tips on locating information within a pre-existing GET array with parameters provided

Apologies for the unclear title. I am currently utilizing a category chooser that pulls categories from an API. The process involves fetching a list of categories, filtering out their names, and presenting them in the category chooser. Upon clicking submit ...

Transmit HTML message using the "textarea" tag through email

Whenever I try to send the content of my "textarea" via email, it always ends up being sent as a blank message. How can I fix this issue? Below is my PHP code: <?php $input = json_decode(file_get_contents("php://input"), true); $ToEmail = "<a href ...

The try and catch block in JavaScript is failing to correctly capture the HTTP status

I have a function that successfully posts JSON to an API endpoint. Here is the code I am using: function sendValuesPageLoad(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { try { if (xhr.readyState === ...

Tips for extracting a JSON element in an Arel query on Postgres in Rails 5.2.4

In my HTML form, I created a helper to populate a drop-down select field. The query is fairly simple, except that the name field has a JSON data type that includes translations in different languages: {"en":"New", "fr":"N ...