user11384069
user11384069

Reputation:

How to parse Json in scala

I want to know how to parse JSON

I am trying to parse json in scala.

But I do not know how to parse

Is there any better way?

key is numbered sequentially from 1

I use circe library...

Thanks

{
  "1": {
    "name": "hoge",
    "num": "60"
  },
  "2": {
    "name": "huga",
    "num": "100"
  },
  "3": {
    "name": "hogehuga",
    "num": "10"
  },
}

Upvotes: 1

Views: 654

Answers (1)

Travis Brown
Travis Brown

Reputation: 139028

Assuming you have a string like this (note that I've removed the trailing comma, which is not valid JSON):

val doc = """
{
  "1": {
    "name": "hoge",
    "num": "60"
  },
  "2": {
    "name": "huga",
    "num": "100"
  },
  "3": {
    "name": "hogehuga",
    "num": "10"
  }
}
"""

You can parse it with circe like this (assuming you've added the circe-jawn module to your build configuration):

scala> io.circe.jawn.parse(doc)
res1: Either[io.circe.ParsingFailure,io.circe.Json] =
Right({
  "1" : {
    "name" : "hoge",
    "num" : "60"
  },
  "2" : {
    "name" : "huga",
    "num" : "100"
  },
  "3" : {
    "name" : "hogehuga",
    "num" : "10"
  }
})

In circe (and some other JSON libraries), the word "parse" is used to refer to transforming strings into a JSON representation (in this case io.circe.Json). It's likely you want something else, like a map to case classes. In circe this kind of transformation to non-JSON-related Scala types is called decoding, and might look like this:

scala> import io.circe.generic.auto._
import io.circe.generic.auto._

scala> case class Item(name: String, num: Int)
defined class Item

scala> io.circe.jawn.decode[Map[Int, Item]](doc)
res2: Either[io.circe.Error,Map[Int,Item]] = Right(Map(1 -> Item(hoge,60), 2 -> Item(huga,100), 3 -> Item(hogehuga,10)))

You can of course decode this JSON into many different Scala representations—if this doesn't work for you please expand your question and I'll update the answer.

Upvotes: 1

Related Questions