SkillAgentSearch skills...

Json4s

JSON library

Install / Use

/learn @json4s/Json4s
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

JSON4S Maven Central

At this moment there are at least 6 json libraries for scala, not counting the java json libraries. All these libraries have a very similar AST. This project aims to provide a single AST to be used by other scala json libraries.

This library got it start as a fork of lift-json aiming to free it from Lift's slower release cycle. However, since then Lift itself has migrated to using json4s directly.

Lift JSON

So the native package in this library is in fact verbatim lift-json in a different package name; this means that your import statements will change if you use this library.

import org.json4s._
import org.json4s.native.JsonMethods._

After that everything works exactly the same as it would with lift-json

Jackson

In addition to the native parser there is also an implementation that uses jackson for parsing to the AST. The jackson module includes most of the jackson-module-scala functionality and the ability to use it with the lift-json AST.

To use jackson instead of the native parser:

import org.json4s._
import org.json4s.jackson.JsonMethods._

Be aware that the default behavior of the jackson integration is to close the stream when it's done. If you want to change that:

import com.fasterxml.jackson.databind.SerializationFeature
org.json4s.jackson.JsonMethods.mapper.configure(SerializationFeature.CLOSE_CLOSEABLE, false)

Guide

Parsing and formatting utilities for JSON.

A central concept in lift-json library is Json AST which models the structure of a JSON document as a syntax tree.

sealed abstract class JValue
case object JNothing extends JValue // 'zero' for JValue
case object JNull extends JValue
case class JString(s: String) extends JValue
case class JDouble(num: Double) extends JValue
case class JDecimal(num: BigDecimal) extends JValue
case class JInt(num: BigInt) extends JValue
case class JLong(num: Long) extends JValue
case class JBool(value: Boolean) extends JValue
case class JObject(obj: List[JField]) extends JValue
case class JArray(arr: List[JValue]) extends JValue

type JField = (String, JValue)

All features are implemented in terms of the above AST. Functions are used to transform the AST itself, or to transform the AST between different formats. Common transformations are summarized in a following picture.

Json AST

Summary of the features:

  • Fast JSON parser
  • LINQ-style queries
  • Case classes can be used to extract values from parsed JSON
  • Diff & merge
  • DSL to produce valid JSON
  • XPath-like expressions and HOFs to manipulate JSON
  • Pretty and compact printing
  • XML conversions
  • Serialization
  • Low-level pull parser API

Installation

You can add the json4s as a dependency in following ways. Note, replace {latestVersion} with correct Json4s version.

You can find available versions here:

https://central.sonatype.com/search?namespace=io.github.json4s

SBT users

For the native support add the following dependency to your project description:

val json4sNative = "io.github.json4s" %% "json4s-native" % "{latestVersion}"

For the Jackson support add the following dependency to your project description:

val json4sJackson = "io.github.json4s" %% "json4s-jackson" % "{latestVersion}"

Maven users

For the native support add the following dependency to your pom:

<dependency>
  <groupId>io.github.json4s</groupId>
  <artifactId>json4s-native_${scala.version}</artifactId>
  <version>{latestVersion}</version>
</dependency>

For the jackson support add the following dependency to your pom:

<dependency>
  <groupId>io.github.json4s</groupId>
  <artifactId>json4s-jackson_${scala.version}</artifactId>
  <version>{latestVersion}</version>
</dependency>

Extras

Support for Enum, Java 8 Date & Time

Support for Joda-Time

Applicative style parsing with Scalaz

Parsing JSON

Any valid json can be parsed into internal AST format. For native support:

scala> import org.json4s._
scala> import org.json4s.native.JsonMethods._

scala> parse(""" { "numbers" : [1, 2, 3, 4] } """)
res0: org.json4s.JValue =
      JObject(List((numbers,JArray(List(JInt(1), JInt(2), JInt(3), JInt(4))))))

scala> parse("""{"name":"Toy","price":35.35}""", useBigDecimalForDouble = true)
res1: org.json4s.JValue =
      JObject(List((name,JString(Toy)), (price,JDecimal(35.35))))

For jackson support:

scala> import org.json4s._
scala> import org.json4s.jackson.JsonMethods._

scala> parse(""" { "numbers" : [1, 2, 3, 4] } """)
res0: org.json4s.JValue =
      JObject(List((numbers,JArray(List(JInt(1), JInt(2), JInt(3), JInt(4))))))

scala> parse("""{"name":"Toy","price":35.35}""", useBigDecimalForDouble = true)
res1: org.json4s.JValue =
      JObject(List((name,JString(Toy)), (price,JDecimal(35.35))))

Producing JSON

You can generate json in 2 modes: either in DoubleMode or in BigDecimalMode; the former will map all decimal values into JDoubles, and the latter into JDecimals.

For the double mode dsl use:

import org.json4s.JsonDSL._
// or
import org.json4s.JsonDSL.WithDouble._

For the big decimal mode dsl use:

import org.json4s.JsonDSL.WithBigDecimal._

DSL rules

  • Primitive types map to JSON primitives.
  • Any seq produces JSON array.
scala> val json = List(1, 2, 3)

scala> compact(render(json))
res0: String = [1,2,3]
  • Tuple2[String, A] produces field.
scala> val json = ("name" -> "joe")

scala> compact(render(json))
res1: String = {"name":"joe"}
  • ~ operator produces object by combining fields.
scala> val json = ("name" -> "joe") ~ ("age" -> 35)

scala> compact(render(json))
res2: String = {"name":"joe","age":35}
  • ~~ operator works the same as ~ and is useful in situations where ~ is shadowed, eg. when using Spray or akka-http.
scala> val json = ("name" -> "joe") ~~ ("age" -> 35)

scala> compact(render(json))
res2: String = {"name":"joe","age":35}
  • Any value can be optional. The field and value are completely removed when it doesn't have a value.
scala> val json = ("name" -> "joe") ~ ("age" -> Some(35))

scala> compact(render(json))
res3: String = {"name":"joe","age":35}

scala> val json = ("name" -> "joe") ~ ("age" -> (None: Option[Int]))

scala> compact(render(json))
res4: String = {"name":"joe"}
  • Extending the dsl

To extend the dsl with your own classes you must have an implicit conversion in scope of signature:

type DslConversion = T => JValue

Example

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._

case class Winner(id: Long, numbers: List[Int])
case class Lotto(id: Long, winningNumbers: List[Int], winners: List[Winner], drawDate: Option[java.util.Date])

object JsonExample {

  val winners = List(Winner(23, List(2, 45, 34, 23, 3, 5)), Winner(54, List(52, 3, 12, 11, 18, 22)))
  val lotto = Lotto(5, List(2, 45, 34, 23, 7, 5, 3), winners, None)

  val json =
    ("lotto" ->
      ("lotto-id" -> lotto.id) ~
      ("winning-numbers" -> lotto.winningNumbers) ~
      ("draw-date" -> lotto.drawDate.map(_.toString)) ~
      ("winners" ->
        lotto.winners.map { w =>
          (("winner-id" -> w.id) ~
           ("numbers" -> w.numbers))}))

  def main(args: Array[String]): Unit = {
    println(compact(render(json)))
  }
}
scala> JsonExample.main(Array.empty[String])
{"lotto":{"lotto-id":5,"winning-numbers":[2,45,34,23,7,5,3],"winners":
[{"winner-id":23,"numbers":[2,45,34,23,3,5]},{"winner-id":54,"numbers":[52,3,12,11,18,22]}]}}

The above example produces the following pretty-printed JSON. Notice that draw-date field is not rendered since its value is None:

scala> pretty(render(JsonExample.json))

{
  "lotto":{
    "lotto-id":5,
    "winning-numbers":[2,45,34,23,7,5,3],
    "winners":[{
      "winner-id":23,
      "numbers":[2,45,34,23,3,5]
    },{
      "winner-id":54,
      "numbers":[52,3,12,11,18,22]
    }]
  }
}

Merging & Diffing

Two JSONs can be merged and diffed with each other. Please see more examples in MergeExamples.scala and DiffExamples.scala.

scala> import org.json4s._
scala> import org.json4s.jackson.JsonMethods._

scala> val lotto1 = parse("""{
         "lotto":{
           "lotto-id":5,
           "winning-numbers":[2,45,34,23,7,5,3],
           "winners":[{
             "winner-id":23,
             "numbers":[2,45,34,23,3,5]
           }]
         }
       }""")

scala> val lotto2 = parse("""{
         "lotto":{
           "winners":[{
             "winner-id":54,
             "numbers":[52,3,12,11,18,22]
           }]
         }
       }""")

scala> val mergedLotto = lotto1 merge lotto2

scala> pretty(render(mergedLotto))
res0: String =
{
  "lotto":{
    "lotto-id":5,
    "winning-numbers":[2,45,34,23,7,5,3],
    "winners":[{
      "winner-id":23,
      "numbers":[2,45,34,23,3,5]
    },{
      "winner-id":54,
      "numbers":[52,3,12,11,18,22]
    }]
  }
}

scala> val Diff(changed, added, deleted) = mergedLotto diff lotto1
changed: org.json4s.JValue = JNothing
added: org.json4s.JValue = JNothing
deleted: org.json4s.JValue = JObject(List((lotto,JObject(List(JField(winners,
JArray(List(JObject(List((winner-id,JInt(54)), (numbers,JArra
View on GitHub
GitHub Stars1.5k
CategoryDevelopment
Updated12h ago
Forks325

Languages

Scala

Security Score

95/100

Audited on Mar 28, 2026

No findings