Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Nov 28 14:29
    scala-steward review_requested #2066
  • Nov 28 14:29
    scala-steward opened #2066
  • Nov 24 14:31
    scala-steward closed #2054
  • Nov 24 14:31
    scala-steward commented #2054
  • Nov 24 14:31
    scala-steward review_requested #2065
  • Nov 24 14:31
    scala-steward opened #2065
  • Nov 24 14:31
    scala-steward closed #2023
  • Nov 24 14:31
    scala-steward commented #2023
  • Nov 24 14:31
    scala-steward commented #1982
  • Nov 24 14:31
    scala-steward review_requested #2064
  • Nov 24 14:31
    scala-steward opened #2064
  • Nov 23 00:06
    morgen-peschke review_requested #2063
  • Nov 23 00:06
    morgen-peschke opened #2063
  • Nov 22 17:16
    morgen-peschke edited #2062
  • Nov 22 17:14
    morgen-peschke opened #2062
  • Nov 22 03:41
    zmccoy commented #1800
  • Nov 22 03:41
    zmccoy commented #1800
  • Nov 22 03:24
    zmccoy commented #1800
  • Nov 21 20:10
    Lasering commented #1800
  • Nov 18 15:48
    scala-steward review_requested #2061
ayeo
@ayeo
I’ve got it :) R: Decoder
blakeh
@blakeh:matrix.org
[m]
Hi friends, I'm using scalajs and crossproject with circe, and I have a stacktrace with circe after making some minor/seemingly unrelated changes. Has anyone by chance seen this before? https://gist.github.com/blakehawkins/12f337514c9cdbc2d86e53729bc9e321
vishakh
@vishakh:cryptonomic.tech
[m]

Hello everyone, is someone able to help me please with my StackOverflow question?

https://stackoverflow.com/questions/73465638/pattern-matching-on-a-scala-case-class-with-type-as-a-field

blakeh
@blakeh:matrix.org
[m]

I didn't try, but you could probably also use rename https://stackoverflow.com/questions/40306107/rename-json-fields-with-circe

But the backticks are fine. That's a scala language-level behavior for escaping reserved keywords

vishakh
@vishakh:cryptonomic.tech
[m]
Thanks, blakeh !
Windymelt
@windymelt

Hi, I love to use this library. I'm going to parse JSON as shapeless' Labelled HList using circe.shapes:

import shapeless._ // for HList syntax
import shapeless.labelled._ // for FieldType
import shapeless.syntax.singleton._ // for ->> syntax

type FB = FieldType["foo", String] :: FieldType["bar", String] :: HNil
val fb: FB = ("foo" ->> "this is foo") :: ("bar" ->> "this is bar") :: HNil
// fb: FB = "this is foo" :: "this is bar" :: HNil

import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
import io.circe.shapes._

val fbj = """{"foo": "hoge", "bar": "fuga"}"""
// fbj: String = "{\"foo\": \"hoge\", \"bar\": \"fuga\"}"
val Right(fb1: FB) = decode[FB](fbj)
// fb1: FB = "hoge" :: "fuga" :: HNil

val fbj2 = """{}"""
// fbj2: String = "{}"
val Left(err) = decode[FB](fbj2)
// err: Error = DecodingFailure(Record, List())

// I'd like to make fields optional:
type OptionalFB =
  FieldType["foo", Option[String]] :: FieldType["bar", Option[String]] :: HNil
val Left(err2) = decode[OptionalFB](fbj2)
// err2: Error = DecodingFailure(Record, List())

// it requires existence of field...
val fbj22 = """{"foo": null, "bar": null}"""
// fbj22: String = "{\"foo\": null, \"bar\": null}"
val Right(ex) = decode[OptionalFB](fbj22)
// ex: OptionalFB = None :: None :: HNil

// Then I captured entire field into Option:
type OptionalFB2 =
  Option[FieldType["foo", String]] :: Option[FieldType["bar", String]] :: HNil
val optionalFB2Example: OptionalFB2 = None :: None :: HNil
// optionalFB2Example: OptionalFB2 = None :: None :: HNil
// However below doesn't compile:
// val Right(fb2) = decode[OptionalFB2](fbj2)

Is there way to decode JSON as Optional Labelled HList? Some of my JSON has optional field, and I want to express optional field in Labelled HList.

Of course, we can decode optional field via case class e.g. case class(foo: Option[String], bar: Option[String]) .
PsyfireX
@PsyfireX
It appears transitive-dependencies of io.circe:circe-optics_2.12:0.14.1 are causing numerous conflicts when attempting to migrate to Scala 3. I don't have that many uses of circe-optics. Am I better off dropping circe-optics? or attempting to play the dependency conflict-resolution game? Or is there some Scala 3 solution for circe-optics that I somehow missed?
[error] Modules were resolved with conflicting cross-version suffixes in ProjectRef(uri("file:/D:/Projects/Git/tag/"), "tag-server"):
[error]    org.typelevel:cats-free _2.13, _3
[error]    io.circe:circe-core _3, _2.13
[error]    org.typelevel:simulacrum-scalafix-annotations _2.13, _3
[error]    org.typelevel:cats-kernel _3, _2.13
[error]    org.typelevel:cats-core _3, _2.13
[error]    io.circe:circe-numbers _3, _2.13
[error] java.lang.RuntimeException: Conflicting cross-version suffixes in: org.typelevel:cats-free, io.circe:circe-core, org.typelevel:simulacrum-scalafix-annotations, org.typelevel:cats-kernel, org.typelevel:cats-core, io.circe:circe-numbers
anqit
@anqit
discussion happens on discord now https://discord.gg/fkjRpApR
ouardateaicha
@ouardateaicha
Hello, i'm trying to deserialize subclasses, but it s failling, any help is welcome : https://scastie.scala-lang.org/2TmNd5SsSey9meo4t81GHQ
Andriy Plokhotnyuk
@plokhotnyuk

As a workaround you can use jsoniter-scala codecs.

They are handy in derivation and much more efficient in the runtime :

import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros._

implicit val codec: JsonValueCodec[Test] = JsonCodecMaker.make(CodecMakerConfig.withDiscriminatorFieldName(None))

println(readFromString[Test](sample))

Full code: https://scastie.scala-lang.org/fZmal0NeSt605Wf4VVS5Kg

Sergiusz Kierat
@sergiuszkierat
[error] sbt.librarymanagement.ResolveException: Error downloading io.circe:circe-generic-extras_2.13:0.14.3
...
[error]   not found: https://repo1.maven.org/maven2/io/circe/circe-generic-extras_2.13/0.14.3/circe-generic-extras_2.13-0.14.3.pom
I can't find this artifact for 0.14.3 release. Can someone check it?
ouardateaicha
@ouardateaicha
@plokhotnyuk Thank you very much, can i inculde readFromString[Test](sample) in my decoder : object Example { implicit val decode: Decoder[Example] = Decoder[ModuleOne].map[Example](identity).or(Decoder[ModuleTwo].map[Example](identity)) so i can call decode ?
Andriy Plokhotnyuk
@plokhotnyuk
@ouardateaicha Unfortunately no, but readFromString call does all parsing and decoding for you.
ouardateaicha
@ouardateaicha
@plokhotnyuk yes, but i need to return a Try like decode and i have a generic converter that uses decode call from many classes..ok thnx i dont know if there is another way to solve this..but very few doc on circe and inheritance
Andriy Plokhotnyuk
@plokhotnyuk
You can wrap readFromString into Try and return Either if you need that: println(scala.util.Try(readFromString[Test](sample)).toEither)
@ouardateaicha Welcome to https://gitter.im/plokhotnyuk/jsoniter-scala if you want to know how easily derive safe and efficient JSON codecs.
ouardateaicha
@ouardateaicha
i have this error :
Maximal number of successive inlines (32) exceeded, Maybe this is caused by a recursive inline method? You can use -Xmax-inlines to change the limit. implicit val decoder:Decoder[Thing] = deriveDecoder[Thing]
i'm using scala 3
and does not change if i add : -Xmax-inlines
any idea?
this is the code throwing this error :
import io.circe.syntax._
    import io.circe.{Decoder, Encoder}
    import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}
    implicit val decoder:Decoder[Thing] = deriveDecoder[Thing]
    implicit val encoder:Encoder[Thing] = deriveEncoder[Thing]
Andriy Plokhotnyuk
@plokhotnyuk
Scala 3 version of circe-generic derivation is limited, so the workaround can be the same as for your previous case. Have you tried if implicit val codec: JsonValueCodec[Thing] = JsonCodecMaker.make works for you?
Sergiusz Kierat
@sergiuszkierat
[error] sbt.librarymanagement.ResolveException: Error downloading io.circe:circe-generic-extras_2.13:0.14.3
...
[error]   not found: https://repo1.maven.org/maven2/io/circe/circe-generic-extras_2.13/0.14.3/circe-generic-extras_2.13-0.14.3.pom

I can't find this artifact for 0.14.3 release. Can someone check it?

stupid me, circe-generic-extras is released independently :facepunch:

ouardateaicha
@ouardateaicha

I have this json :


 {
 "result": 
 {
        "name": "test",
        "foo": {

        },
        "baz": {
        ....
        }

 }

and classes


 case classe fooResult(name : String, foo :Foo)


 object fooResult{
  import io.circe.syntax._
  import io.circe.{Decoder, Encoder}
  import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}
  implicit val decoder:Decoder[fooResult] = deriveDecoder[fooResult]
 }



 case classe Foo (...)

  case classe baz (...)

i want to decode only foo part in the json and not take baz part
i have a code the retrives the whole hson and not only

  "name": "test",
        "foo": {

        }

how can this be achieved?

ScalaWilliam
@ScalaWilliam
fooResult.decoder.map(_.foo) should do the trick

Hi all, how can I do the following with ACursor? The reason for this is running Decoder[..].prepare()

def merge(key1: String, key2: String)(in: ACursor): ACursor

Such that

If we have an object {a: {items in A}, b: {items in B}}, if key1 = a, and key2 = b, then we get back {items in A, deep merged with items in B}?

ouardateaicha
@ouardateaicha
@ScalaWilliam thnx, is it possible to give an example please? thnx
Matthew Tyler
@StrokerAce

Hi - I am trying to derive an encoder for a case class that is a member of a higher kinded sealed trait which also takes a type argument of the same type:

sealed trait Expression[T] {
  def doIt(s: String): Either[String, T]
}

object Expression {
  implicit def lowPriorityEncoder: Encoder[Expression[_]] = deriveEncoder
  implicit def lowPriorityDecoder: Decoder[Expression[_]] = deriveDecoder
  implicit def stringExpressioncoder: Encoder[Expression[String]] = deriveEncoder
  implicit def stringExpressionDecoder: Decoder[Expression[String]] = deriveDecoder
  implicit def booleanExpressionEncoder: Encoder[Expression[Boolean]] = deriveEncoder
  implicit def booleanExpressionDecoder: Decoder[Expression[Boolean]] = deriveDecoder
}

case class X[F[_] <: Expression[_], T](x: F[T]) extends Expression[Boolean] {
  override def doIt(s: String): Either[String, Boolean] = ???
}

object X {
  implicit def typeEncoder[F[_] <: Expression[_], T](implicit FT: Encoder[F[T]]): Encoder[X[F, T]] = deriveEncoder
}

I am unable to derive the encoder for X - can anyone tell me what I am missing or if this is even possible?

ouardateaicha
@ouardateaicha
Hello, is there a way, while traversing Json string using Hcursor, to test for the type of fields :
  val node = c.downField("attribute1").asInstanceOf[HCursor]

  How to do this : 

  if node is of type Text : meaning :  "attribute1"="sdfdfd"

  if node is of type Int : meaning :  "attribute1"=1

  if node is of type Double : meaning :  "attribute1"=0.1

  if node is of type Array : meaning :  "attribute1"=[]

  if node is of type Object : meaning :  "attribute1"={}

  etc..
ouardateaicha
@ouardateaicha
i found it in Json class :
/**
  • The name of the type of the JSON value.
    */
    final def name: String =
    this match {
    case JNull => "Null"
    case JBoolean() => "Boolean"
    case JNumber(
    ) => "Number"
    case JString() => "String"
    case JArray(
    ) => "Array"
    case JObject(_) => "Object"
    }
Fabrice Sznajderman
@Fabszn
hi all
I am migrating one app from scala2 to Scala3 and I am facing with an issue with DeriveEncoder and DeriveDecoder. Compiler ask me something with Mirror.of I don't really get the problem. Their is somethiong special to do when you move from scala2 to Scala3 in case of Circe ?
I don't find any documentation about this in Circe Doc :-/
ScalaWilliam
@ScalaWilliam

@Fabszn can you try to post on the Circe GitHub Issue perhaps? It seems responses here are far and few inbetween, because some people moved to Discord I believe.

If you can also provide a minimal reproduction of the issue you are having that would definitely help resolve the issue.

1 reply
Muse Mekuria
@sumew
How can I configure Circe's encoder/decoders to ignore empty collections? i.e if I have an empty collection, don't create a json representation for it and create an empty collection when the the key is missing in json? Currently I'm forced to use Option[List[A]] for on the scala side
1 reply
ouardateaicha
@ouardateaicha
Hello, where can i find an example of encoder/decoder of Enum in scala 3 with circe?
Clayton Stout
@cfstout

Hi there, I'm attempting to use circe to serialize an ADT. I'm trying to follow the guides, here: https://circe.github.io/circe/codecs/adt.html, but in my use case I have a generic List[T] data type (vs the List[String] in the example). Is there some way to account for this (maybe by asserting that there is an Encoder[T] via an implicit param?) in my code so that things work?

Full code looks something like

  sealed trait FeatureValue extends Any
  object FeatureValue {
    case class BooleanFeature(value: Boolean) extends AnyVal with FeatureValue
    case class DoubleFeature(value: Double) extends AnyVal with FeatureValue
    case class IntFeature(value: Int) extends AnyVal with FeatureValue
    case class StringFeature(value: String) extends AnyVal with FeatureValue
    case class ListFeature[T](value: List[T]) extends FeatureValue
  }

And I'm currently using the circe-shapes method described in the docs

ScalaWilliam
@ScalaWilliam
@cfstout Not possible unless you're decoding into a T for which you already have an Encoder[T].
1 reply
Andriy Plokhotnyuk
@plokhotnyuk
The 1st sample is invalid because JSON arrays cannot have keys.
ouardateaicha
@ouardateaicha

Hello,
I have this json and i wrote those classes and try to decode it

   { 
    "values" : [
      [
        "p1",
        {
          "desc" : "product1",
          "price" : "150",
        }
      ],
      [
        "p2",
        {
          "cl_type" : "product1",
          "price" : "66",

        }
      ]
    ]
  }



case class Test(values : Seq(Arg))

case class Arg (name : String, val:Value)

case class Value (desc : String, price:Int)

Any idea how to decode values which contains array of array ?

Thnx

Andriy Plokhotnyuk
@plokhotnyuk
@ouardateaicha Try if Test(values: Seq[Tuple2[String, Value]]) works for you.
ouardateaicha
@ouardateaicha

Hello,

I have this code where i'm calling get on Option in a Try block.

Is that ok or it s antipattern ?

Thnx

case class Tag(bytes : Array[Byte])

object Tag{

def getBytes(ta:Tag) : Option[Array[Byte]] = {
...//do some comuptation with bytes attributes
}
}


case class Test(desc:String, tag : Tag)


object Test{

def method_2 (value : Tag) : Option[Array[Byte]] = Try{

 val arrayB = new ArrayBuilder.ofByte

arrayBuilder.addAll(Tag.getBytes(value).get)


}.toOption

}
Andriy Plokhotnyuk
@plokhotnyuk
@ouardateaicha Short answer: yes, it is antipattern. General rule: use exceptions when they are 100% exceptional. As an example if you accept an untrusted input and the counterparty is able to make it so that your computation will return None in most cases then your server can overuse CPU like under DoS attack. For more info please read this great article: https://shipilev.net/blog/2014/exceptional-performance/
Andriy Plokhotnyuk
@plokhotnyuk
Just refactored out most of such cases in jsoniter-scala benchmarks to avoid copy-pasting of unsafe solutions plokhotnyuk/jsoniter-scala@06bca43
Barry O'Neill
@barryoneill
Hi everyone - just curious if there's currently a maintainer for circe-optics
it's fallen out of release sync with circe-core. I've tried my best to fix up the necessary upgrades, but it looks like I need a maintainer to approve the CI checks - circe/circe-optics#286
Barry O'Neill
@barryoneill
oh, it appears everyone is on discord now, I'll move my request there.