Search code examples
scalascala.jscirce

Decode JSON with Circe and Scala.js


I try to create veeery simple scala.js app. I was following this tutorial https://www.scala-js.org/doc/tutorial/scalajs-vite.html and I want to decode a json.

Circe https://circe.github.io/circe/ says circe also provides a parser subproject that provides parsing support for Scala.js, with JVM parsing provided by io.circe.jawn and JavaScript parsing from scalajs.js.JSON.

So according to https://circe.github.io/circe/parsing.html I have

import io.circe._
import io.circe.parser._
val myValue = parse(event.data.toString)

and with the following dependencies

"io.circe" %% "circe-core" % "0.14.5",
"io.circe" %% "circe-parser" % "0.14.5",

That gives the following errors

[error] Referring to non-existent class io.circe.parser.package$
[error] Cannot access module for non-module io.circe.parser.package$
[error] Referring to non-existent method 
io.circe.parser.package$.parse(java.lang.String)scala.util.Either

Exactly the same type of error as for JVM only libraries :|


Solution

  • As mentioned in a comment I wrote and that turned out to be correct, Scala.js modules need to be declared with the %%% operator in your sbt build definition, so your two dependencies would need to be declared as follows:

    "io.circe" %%% "circe-core" % "0.14.5",
    "io.circe" %%% "circe-parser" % "0.14.5",
    

    You can read more about it here on the documentation of Scala.js.