### Decode and Encode JSON with circe REPL Example Source: https://circe.github.io/circe/quickstart Demonstrates basic circe usage within an SBT console. It shows how to define case classes, encode them to JSON using `.asJson`, and decode JSON strings back into case classes using `decode`. This example requires `circe-generic.auto` and `circe.syntax` imports. ```Scala import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._ sealed trait Foo case class Bar(xs: Vector[String]) extends Foo case class Qux(i: Int, d: Option[Double]) extends Foo val foo: Foo = Qux(13, Some(14.0)) val json = foo.asJson.noSpaces println(json) val decodedFoo = decode[Foo](json) println(decodedFoo) ``` -------------------------------- ### Serve Circe Microsite Locally Source: https://circe.github.io/circe/contributing After generating the microsite, you can serve it locally for preview. This command navigates to the generated Jekyll directory and starts a local server. ```Shell (cd docs/target/scala-2.12/resource_managed/main/jekyll && jekyll serve -b /circe) ``` -------------------------------- ### Generate Circe Microsite Source: https://circe.github.io/circe/contributing The Circe microsite, featuring examples and design decisions, is generated from markdown files. This requires the sbt build tool and the Jekyll static site generator. ```Shell sbt docs/makeMicrosite ``` -------------------------------- ### Add circe Dependencies to SBT Build Source: https://circe.github.io/circe/quickstart Specifies how to add circe core, generic, and parser modules to your SBT project by defining the circe version and listing the dependencies. This setup is compatible with Scala 2.12, 2.13, and 3.x. ```SBT val circeVersion = "0.14.14" libraryDependencies ++= Seq( "io.circe" %% "circe-core", "io.circe" %% "circe-generic", "io.circe" %% "circe-parser" ).map(_ % circeVersion) ``` -------------------------------- ### Run Circe AtBenchmark Source: https://circe.github.io/circe/api/io/circe/benchmark/AtBenchmark Executes the JMH benchmarks for the AtBenchmark class in Circe, comparing JSON folding performance. This command requires sbt to be installed and configured. ```Shell sbt "benchmark/jmh:run -i 10 -wi 10 -f 2 -t 1 io.circe.benchmark.AtBenchmark" ``` -------------------------------- ### PrintingBenchmark Example Source: https://circe.github.io/circe/api/io/circe/benchmark/PrintingBenchmark Details the PrintingBenchmark class, which is part of the Circe benchmark suite. This benchmark likely compares the performance of different methods for printing or serializing JSON values. ```APIDOC PrintingBenchmark: - Purpose: Compare the performance of various ways of folding JSON values. - Location: io.circe.benchmark.PrintingBenchmark - Related Benchmarks: FoldingBenchmark, InstantiationBenchmark, JsonObjectBenchmark, MapDecoderBenchmark, NumberParsingBenchmark, PointerBenchmark, GenericDerivationBenchmark, AtBenchmark. ``` -------------------------------- ### Circe Pointer Module Overview Source: https://circe.github.io/circe/api/io/circe/pointer/Pointer$$Absolute Provides an overview of the Circe JSON Pointer module, listing its sub-modules and their respective functionalities. It serves as a guide to the different parts of the pointer implementation within Circe. ```APIDOC Package: io.circe.pointer Description: This is the API documentation for Circe, a JSON library for Scala and Scala.js. Modules: - numbers: Core facilities for representing and parsing JSON numbers. - core: JSON abstract syntax tree, cursor types, encoding and decoding type classes. - parser: JSON parsing support for JVM (Jawn) and Scala.js (native JavaScript JSON parser). - testing: ScalaCheck Arbitrary instances for circe's JSON AST and other types. - literal: JSON string interpolation and encoder/decoder instances for literal types. - generic: Shapeless-powered generic derivation for case classes and sealed trait hierarchies. - generic-extras: Additional experimental generic derivation functionality. - pointer: A JSON Pointer implementation. - pointer-literal: JSON Pointer string interpolation. - shapes: Encoders and decoders for Shapeless hlists, coproducts, records, and sized collections. - scodec: Encoders and decoders for Scodec's BitVector and ByteVector. - refined: Encoders and decoders for refined types. - spray: Spray marshaller conversions for Circe's type classes. Refer to the main documentation for a detailed introduction: https://circe.github.io/circe/ ``` -------------------------------- ### Circe Benchmark Examples Source: https://circe.github.io/circe/api/io/circe/benchmark/InstantiationBenchmark This section lists various benchmark classes designed to compare the performance of different Circe operations. These benchmarks cover aspects like JSON folding, generic derivation, object operations, and number parsing. ```APIDOC Circe Benchmark Classes: - AtBenchmark: Compares the performance of various ways of folding JSON values. - ExampleData: Placeholder for example data used in benchmarks. - FoldingBenchmark: Compares the performance of various ways of folding JSON values. - Foo: A simple class, likely used as a test subject. - GenericDerivationBenchmark: Compares the performance of derived and non-derived codecs. - InstantiationBenchmark: Benchmarks object instantiation performance. - JsonObjectBenchmark: Compares the performance of JSON object operations. - MapDecoderBenchmark: Compares the performance of derived and non-derived codecs for map decoding. - NumberParsingBenchmark: Compares the performance of JSON number parsing. - PointerBenchmark: Compares the performance of various ways of folding JSON values using JSON Pointers. - PrintingBenchmark: Compares the performance of string and byte buffer printers. ``` -------------------------------- ### Configure Scala Compiler for @JsonCodec Source: https://circe.github.io/circe/quickstart Details the necessary compiler options for using circe's `@JsonCodec` macro annotations. For Scala 2.13, add `-Ymacro-annotations` to compiler options. For earlier Scala versions, include the Macro Paradise compiler plugin. ```SBT addCompilerPlugin( "org.scalamacros" % "paradise" % "2.1.1" cross CrossVersion.full ) ``` -------------------------------- ### InstantiationBenchmark Class API Source: https://circe.github.io/circe/api/io/circe/benchmark/InstantiationBenchmark API documentation for the InstantiationBenchmark class. This entry details the available methods and fields, their signatures, return types, and associated definition classes. It serves as a reference for interacting with this benchmark class. ```APIDOC InstantiationBenchmark: ensuring(cond: Boolean): InstantiationBenchmark - Description: This member is added by an implicit conversion from InstantiationBenchmark to Ensuring[InstantiationBenchmark] performed by method Ensuring in scala.Predef. - Definition Classes: Ensuring eq(x$1: AnyRef): Boolean - Description: Compares this object to the specified object. The result is true if and only if this object is the same as the specified Object, and false otherwise. - Definition Classes: AnyRef equals(x$1: Object): Boolean - Description: Indicates whether some other object is "equal to" this one. - Definition Classes: AnyRef → Any finalize(): Unit - Description: Called by the garbage collector on the same thread as the finalizable object when finalize() is called on this object. - Attributes: protected[lang] - Definition Classes: AnyRef - Annotations: @throws(classOf[java.lang.Throwable]) formatted(fmtstr: String): String - Description: This member is added by an implicit conversion from InstantiationBenchmark toStringFormat[InstantiationBenchmark] performed by method StringFormat in scala.Predef. - Definition Classes: StringFormat - Annotations: @inline() getClass(): Class[_ <: AnyRef] - Description: Returns the runtime type of this object. - Definition Classes: AnyRef → Any - Annotations: @native() hashCode(): Int - Description: Returns a hash code value for the object. - Definition Classes: AnyRef → Any - Annotations: @native() input: Json - Description: The input JSON value used in the benchmark. - Type: io.circe.Json isInstanceOf[T0]: Boolean - Description: Checked whether the object is an instance of a particular type. - Definition Classes: Any ne(x$1: AnyRef): Boolean - Description: Defers equality to equals, i.e. !(this == x$1). - Definition Classes: AnyRef notify(): Unit - Description: Wakes up a single thread that is waiting on this object's monitor. - Definition Classes: AnyRef - Annotations: @native() notifyAll(): Unit - Description: Wakes up all threads that are waiting on this object's monitor. - Definition Classes: AnyRef - Annotations: @native() synchronized[T0](x$1: =>T0): T0 - Description: Causes the calling thread to block until there is no other thread active in the given object's monitor. - Definition Classes: AnyRef toString(): String - Description: Returns a string representation of the object. - Definition Classes: AnyRef → Any wait(): Unit - Description: Causes the calling thread to wait until it is awakened. - Definition Classes: AnyRef - Annotations: @throws(classOf[java.lang.InterruptedException]) ``` -------------------------------- ### InstantiationBenchmark Methods Source: https://circe.github.io/circe/api/io/circe/benchmark/InstantiationBenchmark Documentation for the InstantiationBenchmark class, detailing its methods related to circe encoding/decoding benchmarks and standard Scala functionalities. Includes method signatures, return types, and annotations. ```APIDOC InstantiationBenchmark: - Represents benchmarks for circe instantiation. Methods: - !=(arg0: Any): Boolean - Final method inherited from AnyRef. - Checks for inequality. - ##: Int - Final method inherited from AnyRef. - Returns the hash code. - +(other: String): String - Implicitly converted from any2stringadd. - Concatenates the instance with a string. - ->[B](y: B): (InstantiationBenchmark, B) - Implicitly converted from ArrowAssoc. - Creates a tuple with the instance and another value. - ==(x$1: Any): Boolean - Final method inherited from AnyRef. - Checks for equality. - asInstanceOf[T0]: T0 - Final method inherited from Any. - Casts the instance to a specific type. - clone(): Object - Protected method inherited from AnyRef. - Creates a copy of the instance. - @throws(classOf[java.lang.CloneNotSupportedException]) @native() - decoderFromInstance: io.circe.Decoder.Result[String] - Benchmark method. - Returns the decoding result for an instance. - @Benchmark() - decoderFromNew: io.circe.Decoder.Result[String] - Benchmark method. - Returns the decoding result for a new object. - @Benchmark() - decoderFromSAM: io.circe.Decoder.Result[String] - Benchmark method. - Returns the decoding result for a SAM (Single Abstract Method). - @Benchmark() - encoderFromInstance: io.circe.Json - Benchmark method. - Returns the JSON representation for an instance. - @Benchmark() - encoderFromNew: io.circe.Json - Benchmark method. - Returns the JSON representation for a new object. - @Benchmark() - encoderFromSAM: io.circe.Json - Benchmark method. - Returns the JSON representation for a SAM. - @Benchmark() - ensuring(cond: A => Boolean, msg: => Any): A - Implicitly converted from Ensuring. - Ensures a condition is met, providing a message on failure. - ensuring(cond: A => Boolean): A - Implicitly converted from Ensuring. - Ensures a condition is met. - ensuring(cond: Boolean, msg: => Any): A - Implicitly converted from Ensuring. - Ensures a boolean condition is met, providing a message on failure. ``` -------------------------------- ### Run InstantiationBenchmark Source: https://circe.github.io/circe/api/io/circe/benchmark/index Compares the performance of various ways of folding JSON values using JMH benchmarks. This command executes the benchmark suite with specified settings for iterations, warmups, forks, and threads. ```sbt sbt "benchmark/jmh:run -i 10 -wi 10 -f 2 -t 1 io.circe.benchmark.DecoderInstantiationBenchmark" ``` -------------------------------- ### Round Trip Failure Example Source: https://circe.github.io/circe/codecs/testing Demonstrates the failure of a round-trip (encoding then decoding) for a Person object when the decoder has a missing or mistyped field, resulting in a DecodingFailure. ```Scala Person("James").asJson.as[Person] // res0: Decoder.Result[Person] = Left( // value = DecodingFailure at .mame: Missing required field // ) ``` -------------------------------- ### Add Circe Parser Dependency Source: https://circe.github.io/circe/parsing To use the parsing module, you need to include a dependency on the `circe-parser` module in your build. This example shows how to add it using sbt. ```Scala libraryDependencies += "io.circe" %% "circe-parser" % "0.14.14" ``` -------------------------------- ### io.circe.benchmark.ExampleData Members Source: https://circe.github.io/circe/api/io/circe/benchmark/ExampleData Documentation for members of the ExampleData class, including standard methods inherited from AnyRef and specific fields like 'booleans' and 'booleansJson'. Each entry details the method/field signature, its definition class, and any implicit conversions or annotations. ```APIDOC ExampleData Members: - !=(arg0: Any): Boolean - Description: Standard inequality check. - Definition Classes: AnyRef → Any - ##: Int - Description: Returns the hash code of an object. - Definition Classes: AnyRef → Any - +(other: String): String - Description: Concatenates the ExampleData instance with a String. - Implicit: Added by implicit conversion from ExampleData to any2stringadd. - Definition Classes: any2stringadd - ->[B](y: B): (ExampleData, B) - Description: Creates a tuple with the ExampleData instance and another value. - Implicit: Added by implicit conversion from ExampleData to ArrowAssoc. - Annotations: @inline() - Definition Classes: ArrowAssoc - ==(x$1: Any): Boolean - Description: Standard equality check. - Definition Classes: AnyRef → Any - asInstanceOf[T0]: T0 - Description: Casts the object to a specified type T0. - Definition Classes: Any - booleans: List[Boolean] - Description: A list of Boolean values. - booleansJson: io.circe.Json - Description: A Circe Json representation of boolean values. - clone(): Object - Description: Creates and returns a copy of this object. - Attributes: protected[lang] - Definition Classes: AnyRef - Annotations: @throws(classOf[java.lang.CloneNotSupportedException]) @native() - ensuring(cond: A => Boolean, msg: => Any): A - Description: Ensures that a condition holds true for the object, providing a custom message on failure. - Implicit: Added by implicit conversion from ExampleData to Ensuring. - Definition Classes: Ensuring - ensuring(cond: A => Boolean): A - Description: Ensures that a condition holds true for the object. - Implicit: Added by implicit conversion from ExampleData to Ensuring. - Definition Classes: Ensuring - ensuring(cond: Boolean, msg: => Any): A - Description: Ensures that a condition holds true, providing a custom message on failure. - Implicit: Added by implicit conversion from ExampleData to Ensuring. - Definition Classes: Ensuring - ensuring(cond: Boolean): A - Description: Ensures that a condition holds true. - Implicit: Added by implicit conversion from ExampleData to Ensuring. - Definition Classes: Ensuring - eq(x$1: AnyRef): Boolean - Description: Tests whether two references point to the same object. - Definition Classes: AnyRef - equals(x$1: Object): Boolean - Description: Compares this object to the specified object. - Definition Classes: AnyRef → Any - finalize(): Unit - Description: Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. - Attributes: protected[lang] - Definition Classes: AnyRef ``` -------------------------------- ### Semi-automatic Codec Derivation Example Source: https://circe.github.io/circe/api/io/circe/generic/semiauto$$DerivationHelper Demonstrates how to use `deriveDecoder` and `deriveEncoder` from `io.circe.generic.semiauto` to automatically derive JSON codecs for Scala case classes. ```Scala import io.circe._, io.circe.generic.semiauto._ case class Foo(i: Int, p: (String, Double)) object Foo { implicit val decodeFoo: Decoder[Foo] = deriveDecoder[Foo] implicit val encodeFoo: Encoder.AsObject[Foo] = deriveEncoder[Foo] } ``` -------------------------------- ### Get Circe Method Name for Encoding (Scala) Source: https://circe.github.io/circe/api/io/circe/generic/Deriver Provides the `TermName` representing the current method's name, used in macro-based encoding logic. ```Scala val encodeMethodName: scala.reflect.macros.Universe.TermName ``` -------------------------------- ### ExampleData Fields and Methods Source: https://circe.github.io/circe/api/io/circe/benchmark/ExampleData This section details the members of the ExampleData class, including its fields and inherited methods from AnyRef and Any. It covers data structures like Maps and Lists, JSON representations, and standard object methods. ```APIDOC ExampleData: Fields: foos: Map[String, Foo] Description: A map of strings to Foo objects. foosJson: Json Description: A circe Json representation of the 'foos' field. helloWorldJson: Json Description: A circe Json representation for 'hello world'. ints: List[Int] Description: A list of integers. intsJson: Json Description: A circe Json representation of the 'ints' field. Methods: formatted(fmtstr: String): String Description: Formats a string based on the provided format string. Parameters: fmtstr: The format string. Returns: The formatted string. getClass(): Class[_] Description: Returns the runtime class of this object. Definition Classes: AnyRef → Any Annotations: @native() Returns: The runtime class. hashCode(): Int Description: Returns a hash code value for the object. Definition Classes: AnyRef → Any Annotations: @native() Returns: The hash code. isInstanceOf[T0]: Boolean Description: Checks if an object is an instance of a particular type. Definition Classes: Any Returns: True if the object is an instance of T0, false otherwise. ne(x$1: AnyRef): Boolean Description: Tests whether this object is the same as another object. Definition Classes: AnyRef Returns: True if the objects are not the same, false otherwise. notify(): Unit Description: Wakes up a single thread that is waiting on this object's monitor. Definition Classes: AnyRef Annotations: @native() notifyAll(): Unit Description: Wakes up all threads that are waiting on this object's monitor. Definition Classes: AnyRef Annotations: @native() synchronized[T0](x$1: => T0): T0 Description: Returns the result of computing the given function while holding the lock for this object. Definition Classes: AnyRef Parameters: arg0: The function to compute. Returns: The result of the function. toString(): String Description: Returns a string representation of the object. Definition Classes: AnyRef → Any Returns: A string representation. wait(): Unit Description: Causes the current thread to wait until it is awakened. Definition Classes: AnyRef Annotations: @throws(classOf[java.lang.InterruptedException]) wait(x$1: Long,x$2: Int): Unit Description: Causes the current thread to wait until it is awakened, or until the given timeout expires. Definition Classes: AnyRef Parameters: arg0: The maximum time to wait in milliseconds. arg1: The maximum time to wait in nanoseconds. Annotations: @throws(classOf[java.lang.InterruptedException]) wait(x$1: Long): Unit Description: Causes the current thread to wait until it is awakened, or until the given timeout expires. Definition Classes: AnyRef Parameters: arg0: The maximum time to wait in milliseconds. Annotations: @throws(classOf[java.lang.InterruptedException]), @native() ``` -------------------------------- ### Run Folding Benchmarks Source: https://circe.github.io/circe/api/io/circe/benchmark/FoldingBenchmark Command to run the JMH benchmarks for FoldingBenchmark with specified settings. ```sbt sbt "benchmark/jmh:run -i 10 -wi 10 -f 2 -t 1 io.circe.benchmark.FoldingBenchmark" ``` -------------------------------- ### Extracting List of Values with Optics Source: https://circe.github.io/circe/optics Example demonstrating how to extract multiple values (quantities of all items) from a JSON array using Circe Optics. The `each` combinator iterates over array elements. ```Scala import io.circe._ import io.circe.parser._ import io.circe.optics.JsonPath._ // Assuming 'json' is defined as in the cursor example val json: Json = parse(""" { "order": { "customer": { "name": "Custy McCustomer", "contactDetails": { "address": "1 Fake Street, London, England", "phone": "0123-456-789" } }, "items": [{ "id": 123, "description": "banana", "quantity": 1 }, { "id": 456, "description": "apple", "quantity": 2 }], "total": 123.45 } } """).getOrElse(Json.Null) val quantities: List[Int] = root.order.items.each.quantity.int.getAll(json) // quantities: List[Int] = List(1, 2) ``` -------------------------------- ### CirceCodecRefined Trait Source: https://circe.github.io/circe/api/io/circe/refined/CirceCodecRefined Provides codecs for refined types. A refined type `T Refined Predicate` is encoded as `T`. Decoding ensures that the decoded value satisfies `Predicate`. Includes an example using generic codecs. ```Scala case class Obj( i: Int Refined Positive ) Obj(refineMV(4)).asJson.noSpaces == "{\"i\":4}" ``` -------------------------------- ### ReprDecoder Constructor and Apply Method Source: https://circe.github.io/circe/api/io/circe/generic/decoding/ReprDecoder Documentation for the ReprDecoder class, including its constructor and the abstract apply method for decoding. ```APIDOC ReprDecoder: __init__(): ReprDecoder[A] Constructs a new ReprDecoder instance. apply(c: HCursor): Decoder.Result[A] Abstract method to decode the given HCursor. Parameters: c: The HCursor to decode from. Returns: A Result indicating success with the decoded value or a DecodingFailure. Definition Classes: Decoder ``` -------------------------------- ### Circe Package Overview (Scala) Source: https://circe.github.io/circe/api/io/circe/Codec$$AsObject$ Provides an overview of the Circe library's modules, including core facilities, JSON AST, encoding/decoding, parsing, testing, and integration with other libraries. It outlines the structure and purpose of each module. ```APIDOC Package: circe Description: This is the API documentation for Circe, a JSON library for Scala and Scala.js. Modules: - numbers: core facilities for representing and parsing JSON numbers. - core: JSON abstract syntax tree, cursor types, encoding and decoding type classes. - parser: JSON parsing support for JVM (Jawn) and Scala.js (native JavaScript JSON parser). - testing: ScalaCheck Arbitrary instances for circe's JSON AST and other types. - literal: JSON string interpolation and encoder/decoder instances for literal types. - generic: Shapeless-powered generic derivation for case classes and sealed trait hierarchies. - generic-extras: Additional experimental generic derivation functionality. - pointer: A JSON Pointer implementation. - pointer-literal: JSON Pointer string interpolation. - shapes: encoders and decoders for Shapeless hlists, coproducts, records, and sized collections. - scodec: encoders and decoders for Scodec's BitVector and ByteVector. - refined: encoders and decoders for refined types. - spray: Spray marshaller conversions for Circe's type classes. Refer to the official documentation for a detailed introduction. ``` -------------------------------- ### Usage of circe-shapes Generic Derivation Source: https://circe.github.io/circe/codecs/adt Demonstrates how to use the generic derivation functions from circe-shapes to encode and decode ADTs. It shows example JSON inputs and outputs for a simple ADT. ```Scala import ShapesDerivation._ import io.circe.parser.decode, io.circe.syntax._ decode[Event]("""{ \"i\": 1000 }""") // res2: Either[io.circe.Error, Event] = Right(value = Foo(i = 1000)) (Foo(100): Event).asJson.noSpaces // res3: String = "{\"i\":100}" ``` -------------------------------- ### Circe Modules Overview Source: https://circe.github.io/circe/api/io/circe/pointer/Pointer$$Relative Overview of the different modules within the Circe JSON library, highlighting their specific functionalities and integration points. ```APIDOC Circe Modules: - numbers: Core facilities for representing and parsing JSON numbers. - core: JSON abstract syntax tree, cursor types, encoding and decoding type classes. - parser: JSON parsing support for JVM (Jawn) and Scala.js (native JSON parser). - testing: ScalaCheck Arbitrary instances for Circe's JSON AST and testing tools. - literal: JSON string interpolation and encoder/decoder instances for literal types. - generic: Shapeless-powered generic derivation for case classes and sealed trait hierarchies. - generic-extras: Additional experimental generic derivation functionality. - pointer: JSON Pointer implementation. - pointer-literal: JSON Pointer string interpolation. - shapes: Encoders and decoders for Shapeless hlists, coproducts, records, and sized collections. - scodec: Encoders and decoders for Scodec's BitVector and ByteVector. - refined: Encoders and decoders for refined types. - spray: Spray marshaller conversions for Circe's type classes. ``` -------------------------------- ### Circe JSON Library Overview Source: https://circe.github.io/circe/api/io/circe/pointer/index Provides an overview of the Circe library, its modules, and links to detailed documentation for each component. It highlights the core functionality and integration points. ```APIDOC Circe Library Overview: - Core functionality: JSON AST, cursor types, encoding/decoding. - Modules: + numbers: Facilities for representing and parsing JSON numbers. + core: JSON AST, cursor types, encoding/decoding type classes. + parser: JSON parsing support for JVM (Jawn) and Scala.js. + testing: ScalaCheck Arbitrary instances for Circe types. + literal: JSON string interpolation and encoder/decoder instances. + generic: Shapeless-powered generic derivation for case classes and sealed traits. + generic-extras: Additional experimental generic derivation functionality. + pointer: JSON Pointer implementation. + pointer-literal: JSON Pointer string interpolation. + shapes: Encoders/decoders for Shapeless hlists, coproducts, records. + scodec: Encoders/decoders for Scodec's BitVector and ByteVector. + refined: Encoders/decoders for Refined types. + spray: Spray marshaller conversions for Circe type classes. - External Resources: + Circe Documentation: https://circe.github.io/circe/ + Circe Parser Source: https://github.com/circe/circe/blob/master/modules/parser/jvm/src/main/scala/io/circe/parser/package.scala + Circe Scodec Source: https://github.com/circe/circe/blob/master/modules/scodec/shared/src/main/scala/io/circe/scodec/package.scala + Circe Refined Source: https://github.com/circe/circe/blob/master/modules/refined/shared/src/main/scala/io/circe/refined/package.scala ``` -------------------------------- ### Double JSON Quantities with Circe Optics (Scala) Source: https://circe.github.io/circe/optics Demonstrates how to modify specific fields within a JSON structure by doubling the quantity values. This example utilizes circe-optics and monocle for targeted modifications. ```scala import io.circe.Json import io.circe.optics.JsonPath._ // Assuming 'json' is a pre-defined Json object // val json: Json = ... val doubleQuantities: Json => Json = root.order.items.each.quantity.int.modify(_ * 2) val modifiedJson = doubleQuantities(json) ``` -------------------------------- ### Run AtBenchmark Source: https://circe.github.io/circe/api/io/circe/benchmark/index Compares the performance of various ways of folding JSON values using JMH benchmarks. This command executes the benchmark suite with specified settings for iterations, warmups, forks, and threads. ```sbt sbt "benchmark/jmh:run -i 10 -wi 10 -f 2 -t 1 io.circe.benchmark.AtBenchmark" ``` -------------------------------- ### Traversing JSON with Optics Source: https://circe.github.io/circe/optics Example showing how to extract a specific value (customer's phone number) using Circe Optics and Monocle. Optics define the traversal path separately from its execution. ```Scala import io.circe._ import io.circe.parser._ import io.circe.optics.JsonPath._ // Assuming 'json' is defined as in the cursor example val json: Json = parse(""" { "order": { "customer": { "name": "Custy McCustomer", "contactDetails": { "address": "1 Fake Street, London, England", "phone": "0123-456-789" } }, "items": [{ "id": 123, "description": "banana", "quantity": 1 }, { "id": 456, "description": "apple", "quantity": 2 }], "total": 123.45 } } """).getOrElse(Json.Null) val _phoneNum = root.order.customer.contactDetails.phone.string // _phoneNum: monocle.package.Optional[Json, String] = monocle.POptional$$anon$1@74aa16ef val phoneNum: Option[String] = _phoneNum.getOption(json) // phoneNum: Option[String] = Some(value = "0123-456-789") ``` -------------------------------- ### Extracting Parse Result from Either Source: https://circe.github.io/circe/parsing You can extract the parsed JSON from the `Either` result using pattern matching or extension methods like `getOrElse` provided by libraries like Cats. This example demonstrates both approaches. ```Scala import io.circe._ import io.circe.parser._ val rawJson: String = """ { "foo": "bar", "baz": 123, "list of stuff": [ 4, 5, 6 ] } """ // Using pattern matching parse(rawJson) match { case Left(failure) => println("Invalid JSON :(") case Right(json) => println("Yay, got some JSON!") } // Yay, got some JSON! // Using getOrElse (requires Cats) val json: Json = parse(rawJson).getOrElse(Json.Null) // json: Json = JObject(...) ``` -------------------------------- ### Circe Library Overview Source: https://circe.github.io/circe/api/io/circe/generic/util/PatchWithOptions Overview of Circe's modules and their functionalities, including core JSON handling, parsing, testing, and integration with other libraries. ```APIDOC Circe Library Modules: - numbers: Core facilities for representing and parsing JSON numbers. - core: JSON abstract syntax tree, zipper-like cursor types, and encoding/decoding type classes. - parser: JSON parsing support for JVM (Jawn) and Scala.js (native JavaScript JSON parser). - testing: ScalaCheck Arbitrary instances for Circe's JSON AST and other testing tools. - literal: JSON string interpolation and encoder/decoder instances for literal types. - generic: Shapeless-powered generic derivation for case classes and sealed trait hierarchies. - generic-extras: Additional experimental generic derivation functionality. - pointer: A JSON Pointer implementation. - pointer-literal: JSON Pointer string interpolation. - shapes: Encoders and decoders for Shapeless hlists, coproducts, records, and sized collections. - scodec: Encoders and decoders for Scodec's BitVector and ByteVector. - refined: Encoders and decoders for refined types. - spray: Spray marshaller conversions for Circe's type classes. Refer to the official documentation for a detailed introduction: https://circe.github.io/circe/ ``` -------------------------------- ### Extract Data using HCursor Source: https://circe.github.io/circe/cursors Shows how to create an HCursor from a Json object and use methods like downField, as, get, and downArray to navigate and extract specific data values from the JSON structure. ```scala import io.circe.Decoder // Assuming 'doc' is a Json object obtained from parsing val cursor: HCursor = doc.hcursor // Extracting a Double value from a nested field val baz: Decoder.Result[Double] = cursor.downField("values").downField("baz").as[Double] // baz: Decoder.Result[Double] = Right(value = 100.001) // Using get as a shorthand for downField and as val baz2: Decoder.Result[Double] = cursor.downField("values").get[Double]("baz") // baz2: Decoder.Result[Double] = Right(value = 100.001) // Extracting a String from an array element val secondQux: Decoder.Result[String] = cursor.downField("values").downField("qux").downArray.as[String] // secondQux: Decoder.Result[String] = Right(value = "a") ``` -------------------------------- ### Circe Library Modules Overview Source: https://circe.github.io/circe/api/io/circe/pointer/Pointer$$Relative$$Result$$Json Lists and describes the various modules available in the Circe JSON library, covering core functionality, parsing, testing, generic derivation, JSON Pointer, and integrations with other libraries. ```APIDOC Circe Library Modules: - numbers: Core facilities for representing and parsing JSON numbers. - core: JSON abstract syntax tree, cursor types, and encoding/decoding type classes. - parser: JSON parsing support for JVM (Jawn) and Scala.js (native JSON parser). - testing: ScalaCheck Arbitrary instances for Circe's JSON AST and other testing tools. - literal: JSON string interpolation and encoder/decoder instances for literal types. - generic: Shapeless-powered generic derivation for case classes and sealed trait hierarchies. - generic-extras: Additional experimental generic derivation functionality. - pointer: A JSON Pointer implementation. - pointer-literal: JSON Pointer string interpolation. - shapes: Encoders and decoders for Shapeless hlists, coproducts, records, and sized collections. - scodec: Encoders and decoders for Scodec's BitVector and ByteVector. - refined: Encoders and decoders for refined types. - spray: Spray marshaller conversions for Circe's type classes. ``` -------------------------------- ### Traversing JSON with Cursors Source: https://circe.github.io/circe/optics Example demonstrating how to traverse a JSON document to extract a specific value (customer's phone number) using Circe's cursor API. This method involves chaining downField calls. ```Scala import io.circe._ import io.circe.parser._ val json: Json = parse(""" { "order": { "customer": { "name": "Custy McCustomer", "contactDetails": { "address": "1 Fake Street, London, England", "phone": "0123-456-789" } }, "items": [{ "id": 123, "description": "banana", "quantity": 1 }, { "id": 456, "description": "apple", "quantity": 2 }], "total": 123.45 } } """).getOrElse(Json.Null) val phoneNumFromCursor: Option[String] = json.hcursor. downField("order"). downField("customer"). downField("contactDetails"). get[String]("phone"). toOption // phoneNumFromCursor: Option[String] = Some(value = "0123-456-789") ``` -------------------------------- ### Circe Modules Overview Source: https://circe.github.io/circe/api/io/circe/pointer/Pointer$$Relative$$Result Overview of the different modules available in the Circe JSON library, detailing their specific functionalities and dependencies. ```APIDOC Modules: - numbers: Core facilities for representing and parsing JSON numbers. - core: JSON abstract syntax tree, zipper-like cursor types, and encoding/decoding type classes. - parser: JSON parsing support for JVM (Jawn) and Scala.js (native JavaScript JSON parser). - testing: ScalaCheck Arbitrary instances for Circe's JSON AST and other types. - literal: JSON string interpolation and encoder/decoder instances for literal types. - generic: Shapeless-powered generic derivation for case classes and sealed trait hierarchies. - generic-extras: Additional experimental generic derivation functionality. - pointer: A JSON Pointer implementation. - pointer-literal: JSON Pointer string interpolation. - shapes: Encoders and decoders for Shapeless hlists, coproducts, records, and sized collections. - scodec: Encoders and decoders for Scodec's BitVector and ByteVector. - refined: Encoders and decoders for refined types. - spray: Spray marshaller conversions for Circe's type classes. ``` -------------------------------- ### Circe Pointer Class Methods Source: https://circe.github.io/circe/api/io/circe/pointer/Pointer This section details the various methods provided by the Circe Pointer class for JSON manipulation. It includes methods for getting values, formatting pointers, and standard object methods inherited from AnyRef and Any. ```APIDOC Pointer Class Methods: finalize(): Unit - Description: Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. - Annotations: @throws(classOf[java.lang.Throwable]) formatted(fmtstr: String): String - Description: Formats the pointer using a given string format. - Implicit: Added by an implicit conversion from Pointer toStringFormat[Pointer] performed by method StringFormat in scala.Predef. - Definition Classes: StringFormat - Annotations: @inline() get(input: Json): Either[PointerFailure, Json] - Description: Attempt to get the value at the location pointed to, returning the history if it doesn't exist. - Parameters: - input: The JSON input to navigate. - Returns: An Either type, containing PointerFailure on error or the Json value if successful. getClass(): Class[_] - Description: Returns the runtime class of this object. - Definition Classes: AnyRef → Any - Annotations: @native() hashCode(): Int - Description: Returns a hash code value for the object. - Definition Classes: AnyRef → Any - Annotations: @native() isInstanceOf[T0]: Boolean - Description: Checks if an object is an instance of a particular type. - Definition Classes: Any ne(x$1: AnyRef): Boolean - Description: Tests whether two references refer to the same object. - Definition Classes: AnyRef notify(): Unit - Description: Wakes up a single thread that is waiting on this object's monitor. - Definition Classes: AnyRef - Annotations: @native() notifyAll(): Unit - Description: Wakes up all threads that are waiting on this object's monitor. - Definition Classes: AnyRef - Annotations: @native() synchronized[T0](x$1: =>T0): T0 - Description: Causes the current thread to wait until it is awakened. - Definition Classes: AnyRef toString(): String - Description: Returns a string representation of the object. - Definition Classes: Function1 → AnyRef → Any wait(): Unit - Description: Causes the currently running thread to sleep until it is awakened. - Definition Classes: AnyRef - Annotations: @throws(classOf[java.lang.InterruptedException]) wait(x$1: Long,x$2: Int): Unit - Description: Causes the current thread to wait until it is awakened, or until the timeout expires. - Parameters: - arg0: The maximum time to wait in milliseconds. - arg1: The maximum time to wait in nanoseconds. - Definition Classes: AnyRef - Annotations: @throws(classOf[java.lang.InterruptedException]) wait(x$1: Long): Unit - Description: Causes the current thread to wait until it is awakened, or until the timeout expires. - Parameters: - arg0: The maximum time to wait in milliseconds. - Definition Classes: AnyRef - Annotations: @throws(classOf[java.lang.InterruptedException]) @native() Deprecated Value Members: →[B](y: B): (Pointer, B) - Description: Deprecated method for creating an arrow association. - Deprecated: *(Since version 2.13.0)* Use `->` instead. If you still wish to display it as one character, consider using a font with programming ligatures such as Fira Code. - Implicit: Added by an implicit conversion from Pointer to ArrowAssoc[Pointer] performed by method ArrowAssoc in scala.Predef. - Definition Classes: ArrowAssoc - Annotations: @deprecated Inherited from (ACursor) => ACursor Inherited from AnyRef Inherited from Any ``` -------------------------------- ### Circe Modules Overview Source: https://circe.github.io/circe/api/io/circe/scalajs/index Overview of the different modules available in the Circe library, detailing their specific functionalities and integrations. ```APIDOC Circe Modules: - numbers: Core facilities for representing and parsing JSON numbers. - core: JSON abstract syntax tree, zipper-like cursor types, and encoding/decoding type classes. - parser: JSON parsing support for JVM (Jawn) and Scala.js (native JavaScript JSON parser). - testing: ScalaCheck Arbitrary instances for Circe's JSON AST and other testing tools. - literal: JSON string interpolation and encoder/decoder instances for literal types. - generic: Shapeless-powered generic derivation for case classes and sealed trait hierarchies. - generic-extras: Additional experimental generic derivation functionality. - pointer: A JSON Pointer implementation. - pointer-literal: JSON Pointer string interpolation. - shapes: Encoders and decoders for Shapeless hlists, coproducts, records, and sized collections. - scodec: Encoders and decoders for Scodec's BitVector and ByteVector. - refined: Encoders and decoders for refined types. - spray: Spray marshaller conversions for Circe's type classes. ``` -------------------------------- ### Circe Modules Overview Source: https://circe.github.io/circe/api/io/circe/benchmark/NumberParsingBenchmark Overview of Circe's modular structure, detailing core facilities, JSON AST, cursors, encoding/decoding, parsing support, testing tools, literal JSON, generic derivation, JSON Pointer implementation, and integration with libraries like Shapeless, Scodec, refined, and Spray. ```APIDOC Circe Modules: - numbers: Core facilities for representing and parsing JSON numbers. - core: JSON abstract syntax tree, zipper-like cursor types, and encoding/decoding type classes. - parser: JSON parsing support for JVM (Jawn) and Scala.js (native JavaScript JSON parser). - testing: ScalaCheck Arbitrary instances for Circe's JSON AST and other types, plus testing tools. - literal: JSON string interpolation and encoder/decoder instances for literal types. - generic: Shapeless-powered generic derivation for case classes and sealed trait hierarchies. - generic-extras: Additional experimental generic derivation functionality. - pointer: A JSON Pointer implementation. - pointer-literal: JSON Pointer string interpolation. - shapes: Encoders and decoders for Shapeless hlists, coproducts, records, and sized collections. - scodec: Encoders and decoders for Scodec's BitVector and ByteVector. - refined: Encoders and decoders for refined types. - spray: Spray marshaller conversions for Circe's type classes. ``` -------------------------------- ### Run GenericDerivationBenchmark Source: https://circe.github.io/circe/api/io/circe/benchmark/index Compares the performance of derived and non-derived codecs using JMH benchmarks. This command executes the benchmark suite with specified settings for iterations, warmups, forks, and threads. ```sbt sbt "benchmark/jmh:run -i 10 -wi 10 -f 2 -t 1 io.circe.benchmark.GenericDerivationBenchmark" ```