Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a json string to a scala map?

I have a nested json whose structure is not defined. It can be different each time I run since I am reading from a remote file. I need to convert this json into a map of type Map[String, Any]. I tried to look into json4s and jackson parsers but they don't seem to solve this issue I have. Does anyone know how I can achieve this?

Example string:

{"body":{
    "method":"string",
    "events":"string",
    "clients":"string",
    "parameter":"string",
    "channel":"string",
    "metadata":{
        "meta1":"string",
        "meta2":"string",
        "meta3":"string"
    }
},
"timestamp":"string"}

The level of nesting can be arbitrary and not predefined.
To help with the use case:
I have a Map[String,Any] which I need to store in a file as backup. So I convert it to a json string and store it in a file. Now everytime I get new data, I need to get the json from the file, convert it to a map again and perform some computation. I cannot store the map in memory since I would lose that if my job fails.
I need a solution that would convert the json string back to the original map I had before i converted it.

like image 629
Udit Mehta Avatar asked Apr 28 '15 00:04

Udit Mehta


People also ask

Can we convert JSON to map?

We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.

How do I convert a JSON to a string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

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.


2 Answers

I tried the following method with json4s 3.2.11 and it works:

import org.json4s._
import org.json4s.jackson.JsonMethods._

//...
def jsonStrToMap(jsonStr: String): Map[String, Any] = {
  implicit val formats = org.json4s.DefaultFormats

  parse(jsonStr).extract[Map[String, Any]]
}

Maybe you didn't define the implicit val of type Formats? Note also that you don't need to have an implicit val within every and each method as long as it's findable in the scope.

like image 178
lambdista Avatar answered Sep 18 '22 04:09

lambdista


You can use the following code to parse a JSON string into a Map[String, Any]

val jsonMap = parse(jsonString).values.asInstanceOf[Map[String, Any]]

However, this is not typesafe and hence should be used with caution when extracting values from the map.

like image 39
user297112 Avatar answered Sep 20 '22 04:09

user297112