1

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"
  },
}
3
  • Please share your code. We can't find mistakes in your code if you haven't added it. Commented Apr 19, 2019 at 13:36
  • Can you paste your Circe code? Are you trying to parse it to a case class? If so, Scala doesn't support numbers as attribute names, so your case class should have escaped named like case class Foo(`1`: Int) Commented Apr 19, 2019 at 15:24
  • Possible duplicate of How does circe parse a generic type object to Json? Commented May 12, 2019 at 1:00

1 Answer 1

1

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.

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.