grapple.json

package grapple.json

Type members

Classlikes

object Json

Provides JSON utilities.

Provides JSON utilities.

import scala.language.implicitConversions

import grapple.json.{ *, given }

// Create JSON object
val user = Json.obj("id" -> 1000, "name" -> "lupita")

// Create JSON array
val info = Json.arr(user, "/home/lupita", 8L * 1024 * 1024 * 1024)

// Parse JSON text
val root = Json.parse("""{ "id": 0, "name": "root" }""")

case class User(id: Int, name: String)

given userOutput: JsonOutput[User] with
 def write(u: User) = Json.obj("id" -> u.id, "name" -> u.name)

// Convert value to JSON object
val nobody = Json.toJson(User(65534, "nobody"))
trait JsonAdapter[T] extends JsonInput[T] with JsonOutput[T]

Defines JSON input and output conversions.

Defines JSON input and output conversions.

trait JsonArray extends JsonStructure

Defines JSON array.

Defines JSON array.

See also:
Companion:
object
object JsonArray

Provides JSON array factory.

Provides JSON array factory.

Companion:
class

Defines JSON array builder.

Defines JSON array builder.

import scala.language.implicitConversions

import grapple.json.{ *, given }

val user = JsonArrayBuilder()
 .add(1000)
 .add("lupita")
 .add(Set("lupita", "sudoer"))
 .build()

assert { user(0).as[Int] == 1000 }
assert { user(1).as[String] == "lupita" }
assert { user(2).as[Set[String]] == Set("lupita", "sudoer") }
See also:
sealed trait JsonBoolean extends JsonValue

Defines JSON boolean.

Defines JSON boolean.

Companion:
object

Provides JSON boolean factory.

Provides JSON boolean factory.

Companion:
class
class JsonException(message: String, cause: Throwable) extends RuntimeException

Defines JSON exception.

Defines JSON exception.

Value parameters:
cause

underlying cause

message

detail message

Constructor:

Constructs exception with detail message and underlying cause.

case object JsonFalse extends JsonBoolean

Represents JSON false.

Represents JSON false.

trait JsonGenerator extends AutoCloseable

Defines JSON generator.

Defines JSON generator.

import java.io.StringWriter

import scala.language.implicitConversions

import grapple.json.{ *, given }

val buf = StringWriter()
val out = JsonGenerator(buf)

try
 out.writeStartObject()          // start root object
 out.write("id", 1000)
 out.write("name", "lupita")
 out.writeStartArray("groups")   // start nested array
 out.write("lupita")
 out.write("admin")
 out.write("sudoer")
 out.writeEnd()                  // end nested array
 out.writeStartObject("info")    // start nested object
 out.write("home", "/home/lupita")
 out.write("storage", "8 GiB")
 out.writeEnd()                  // end nested object
 out.writeEnd()                  // end root object
 out.flush()

 val json = Json.parse(buf.toString)
 assert { json("id") == JsonNumber(1000) }
 assert { json("name") == JsonString("lupita") }
 assert { json("groups") == Json.arr("lupita", "admin", "sudoer") }
 assert { json("info") == Json.obj("home" -> "/home/lupita", "storage" -> "8 GiB") }
finally
 out.close()
See also:
Companion:
object

Provides JSON generator factory.

Provides JSON generator factory.

Companion:
class
case class JsonGeneratorError(message: String) extends JsonException

Defines JSON generator error.

Defines JSON generator error.

Value parameters:
message

detail message

@FunctionalInterface
trait JsonInput[T]

Defines JSON input conversion.

Defines JSON input conversion.

import scala.language.implicitConversions

import grapple.json.{ *, given }

case class User(id: Int, name: String)

// Define how to convert JsonValue to User
given userInput: JsonInput[User] =
 case json: JsonObject => User(json("id"), json("name"))
 case _                => throw IllegalArgumentException("Expected JSON object")

val json = Json.obj("id" -> 0, "name" -> "root")
assert { json.as[User] == User(0, "root") }
See also:
sealed trait JsonNull extends JsonValue

Defines JSON null.

Defines JSON null.

Companion:
object
case object JsonNull extends JsonNull

Represents JSON null.

Represents JSON null.

Companion:
class
trait JsonNumber extends JsonValue

Defines JSON number.

Defines JSON number.

Companion:
object
object JsonNumber

Provides JSON number factory.

Provides JSON number factory.

Companion:
class

Defines JSON object.

Defines JSON object.

See also:
Companion:
object
object JsonObject

Provides JSON object factory.

Provides JSON object factory.

Companion:
class

Defines JSON object builder.

Defines JSON object builder.

import scala.language.implicitConversions

import grapple.json.{ *, given }

val user = JsonObjectBuilder()
 .add("id", 1000)
 .add("name", "lupita")
 .add("groups", Set("lupita", "sudoer"))
 .build()

assert { user("id").as[Int] == 1000 }
assert { user("name").as[String] == "lupita" }
assert { user("groups").as[Set[String]] == Set("lupita", "sudoer") }
See also:
@FunctionalInterface
trait JsonOutput[T]

Defines JSON output conversion.

Defines JSON output conversion.

import scala.language.implicitConversions

import grapple.json.{ *, given }

case class User(id: Int, name: String)

// Define how to convert User to JsonValue
given userOutput: JsonOutput[User] =
 user => Json.obj("id" -> user.id, "name" -> user.name)

val users = Json.arr(User(0, "root"), User(1000, "lupita"))
assert { users(0) == Json.obj("id" -> 0, "name" -> "root") }
assert { users(1) == Json.obj("id" -> 1000, "name" -> "lupita") }
See also:
trait JsonParser extends Iterator[Event] with AutoCloseable

Defines JSON parser.

Defines JSON parser.

import scala.language.implicitConversions

import grapple.json.{ *, given }
import grapple.json.JsonParser.Event

val parser = JsonParser("""{ "id": 1000, "name": "lupita", "groups": ["lupita", "admin"] }""")

try
 // Get first event (start root object)
 assert { parser.next() == Event.StartObject }

 // Get field name and value
 assert { parser.next() == Event.FieldName("id") }
 assert { parser.next() == Event.Value(1000) }

 // Get field name and value
 assert { parser.next() == Event.FieldName("name") }
 assert { parser.next() == Event.Value("lupita") }

 // Get field name and value
 assert { parser.next() == Event.FieldName("groups") }
 assert { parser.next() == Event.StartArray } // start nested array
 assert { parser.next() == Event.Value("lupita") }
 assert { parser.next() == Event.Value("admin") }
 assert { parser.next() == Event.EndArray }   // end nested array

 // Get final event (end root object)
 assert { parser.next() == Event.EndObject }

 // No more events
 assert { !parser.hasNext }
finally
 parser.close()
See also:
Companion:
object
object JsonParser

Provides JSON parser factory and other utilities.

Provides JSON parser factory and other utilities.

Companion:
class
case class JsonParserError(message: String, offset: Long) extends JsonException

Defines JSON parser error.

Defines JSON parser error.

Value parameters:
message

detail message

offset

character offset of parser error

trait JsonReader extends AutoCloseable

Defines JSON reader.

Defines JSON reader.

import scala.language.implicitConversions

import grapple.json.{ *, given }

val in = JsonReader("""{ "id": 1000, "name": "lupita" }""")

try
 val user = in.read()
 assert { user("id").as[Int] == 1000 }
 assert { user("name").as[String] == "lupita" }
finally
 in.close()
See also:
Companion:
object
object JsonReader

Provides JSON reader factory.

Provides JSON reader factory.

Companion:
class
trait JsonString extends JsonValue

Defines JSON string.

Defines JSON string.

Companion:
object
object JsonString

Provides JSON string factory.

Provides JSON string factory.

Companion:
class
sealed trait JsonStructure extends JsonValue

Defines JSON structure.

Defines JSON structure.

case object JsonTrue extends JsonBoolean

Represents JSON true.

Represents JSON true.

sealed trait JsonValue

Defines JSON value.

Defines JSON value.

trait JsonWriter extends AutoCloseable

Defines JSON writer.

Defines JSON writer.

import java.io.StringWriter

import scala.language.implicitConversions

import grapple.json.{ *, given }

val buf = StringWriter()
val out = JsonWriter(buf)

try
 val user = Json.obj("id" -> 1000, "name" -> "lupita")
 out.write(user)

 val json = Json.parse(buf.toString)
 assert { json == user }
finally
 out.close()
See also:
Companion:
object
object JsonWriter

Provides JSON writer factory.

Provides JSON writer factory.

Companion:
class
object bigDecimalToJsonNumber extends JsonOutput[BigDecimal]

Converts BigDecimal to JsonNumber.

Converts BigDecimal to JsonNumber.

object bigIntToJsonNumber extends JsonOutput[BigInt]

Converts BigInt to JsonNumber.

Converts BigInt to JsonNumber.

object booleanToJsonBoolean extends JsonOutput[Boolean]

Converts Boolean to JsonBoolean.

Converts Boolean to JsonBoolean.

object byteToJsonNumber extends JsonOutput[Byte]

Converts Byte to JsonNumber.

Converts Byte to JsonNumber.

object doubleToJsonNumber extends JsonOutput[Double]

Converts Double to JsonNumber.

Converts Double to JsonNumber.

object failureToJsonNull extends JsonOutput[Failure[_]]

Converts Failure to JsonNull.

Converts Failure to JsonNull.

object floatToJsonNumber extends JsonOutput[Float]

Converts Float to JsonNumber.

Converts Float to JsonNumber.

object intToJsonNumber extends JsonOutput[Int]

Converts Int to JsonNumber.

Converts Int to JsonNumber.

object jsonValueToBigDecimal extends JsonInput[BigDecimal]

Converts JsonValue to BigDecimal.

Converts JsonValue to BigDecimal.

object jsonValueToBigInt extends JsonInput[BigInt]

Converts JsonValue to BigInt.

Converts JsonValue to BigInt.

object jsonValueToBoolean extends JsonInput[Boolean]

Converts JsonValue to Boolean.

Converts JsonValue to Boolean.

object jsonValueToByte extends JsonInput[Byte]

Converts JsonValue to Byte.

Converts JsonValue to Byte.

object jsonValueToDouble extends JsonInput[Double]

Converts JsonValue to Double.

Converts JsonValue to Double.

object jsonValueToFloat extends JsonInput[Float]

Converts JsonValue to Float.

Converts JsonValue to Float.

object jsonValueToInt extends JsonInput[Int]

Converts JsonValue to Int.

Converts JsonValue to Int.

Casts JsonValue to JsonArray.

Casts JsonValue to JsonArray.

Casts JsonValue to JsonBoolean.

Casts JsonValue to JsonBoolean.

Casts JsonValue to JsonNull.

Casts JsonValue to JsonNull.

Casts JsonValue to JsonNumber.

Casts JsonValue to JsonNumber.

Casts JsonValue to JsonObject.

Casts JsonValue to JsonObject.

Casts JsonValue to JsonString.

Casts JsonValue to JsonString.

Returns JsonValue as is.

Returns JsonValue as is.

This instance is required to perform actions such as the following:

import scala.language.implicitConversions

import grapple.json.{ Json, JsonValue, given }

val json = Json.obj("values" -> Json.arr("abc", 123, true))

// Requires jsonValueToJsonValue
val list = json("values").as[List[JsonValue]]
object jsonValueToLong extends JsonInput[Long]

Converts JsonValue to Long.

Converts JsonValue to Long.

object jsonValueToShort extends JsonInput[Short]

Converts JsonValue to Short.

Converts JsonValue to Short.

object jsonValueToString extends JsonInput[String]

Converts JsonValue to String.

Converts JsonValue to String.

object longToJsonNumber extends JsonOutput[Long]

Converts Long to JsonNumber.

Converts Long to JsonNumber.

object noneToJsonNull extends JsonOutput[None.type]

Converts None to JsonNull.

Converts None to JsonNull.

object shortToJsonNumber extends JsonOutput[Short]

Converts Short to JsonNumber.

Converts Short to JsonNumber.

object stringToJsonString extends JsonOutput[String]

Converts String to JsonString.

Converts String to JsonString.

Givens

Givens

given arrayToJsonArray[T](using converter: JsonOutput[T]): arrayToJsonArray[T]

Converts Array to JsonArray.

Converts Array to JsonArray.

Converts BigDecimal to JsonNumber.

Converts BigDecimal to JsonNumber.

Converts BigInt to JsonNumber.

Converts BigInt to JsonNumber.

Converts Boolean to JsonBoolean.

Converts Boolean to JsonBoolean.

Converts Byte to JsonNumber.

Converts Byte to JsonNumber.

Converts Double to JsonNumber.

Converts Double to JsonNumber.

given eitherToJsonValue[A, B, M <: (Either)](using left: JsonOutput[A])(using right: JsonOutput[B]): eitherToJsonValue[A, B, M]

Converts Right to JsonValue using right converter or converts Left using left.

Converts Right to JsonValue using right converter or converts Left using left.

Converts Failure to JsonNull.

Converts Failure to JsonNull.

Converts Float to JsonNumber.

Converts Float to JsonNumber.

Converts Int to JsonNumber.

Converts Int to JsonNumber.

given iterableToJsonArray[T, M <: (Iterable)](using converter: JsonOutput[T]): iterableToJsonArray[T, M]

Converts Iterable to JsonArray.

Converts Iterable to JsonArray.

given jsonInputConversion[T](using converter: JsonInput[T]): jsonInputConversion[T]

Applies conversion using JsonInput.

Applies conversion using JsonInput.

given jsonOutputConversion[T](using converter: JsonOutput[T]): jsonOutputConversion[T]

Applies conversion using JsonOutput.

Applies conversion using JsonOutput.

Converts JsonValue to BigDecimal.

Converts JsonValue to BigDecimal.

Converts JsonValue to BigInt.

Converts JsonValue to BigInt.

Converts JsonValue to Boolean.

Converts JsonValue to Boolean.

Converts JsonValue to Byte.

Converts JsonValue to Byte.

given jsonValueToCollection[T, M[T]](using converter: JsonInput[T])(using factory: Factory[T, M[T]]): jsonValueToCollection[T, M]

Converts JsonValue to collection of converted values.

Converts JsonValue to collection of converted values.

Converts JsonValue to Double.

Converts JsonValue to Double.

given jsonValueToEither[A, B](using left: JsonInput[A])(using right: JsonInput[B]): jsonValueToEither[A, B]

Converts JsonValue to Right using right converter or to Left using left if right is unsuccessful.

Converts JsonValue to Right using right converter or to Left using left if right is unsuccessful.

Converts JsonValue to Float.

Converts JsonValue to Float.

Converts JsonValue to Int.

Converts JsonValue to Int.

Casts JsonValue to JsonArray.

Casts JsonValue to JsonArray.

Casts JsonValue to JsonBoolean.

Casts JsonValue to JsonBoolean.

Casts JsonValue to JsonNull.

Casts JsonValue to JsonNull.

Casts JsonValue to JsonNumber.

Casts JsonValue to JsonNumber.

Casts JsonValue to JsonObject.

Casts JsonValue to JsonObject.

Casts JsonValue to JsonString.

Casts JsonValue to JsonString.

Returns JsonValue as is.

Returns JsonValue as is.

This instance is required to perform actions such as the following:

import scala.language.implicitConversions

import grapple.json.{ Json, JsonValue, given }

val json = Json.obj("values" -> Json.arr("abc", 123, true))

// Requires jsonValueToJsonValue
val list = json("values").as[List[JsonValue]]

Converts JsonValue to Long.

Converts JsonValue to Long.

given jsonValueToOption[T](using converter: JsonInput[T]): jsonValueToOption[T]

Converts JsonValue to Some or returns None if value is JsonNull.

Converts JsonValue to Some or returns None if value is JsonNull.

Converts JsonValue to Short.

Converts JsonValue to Short.

Converts JsonValue to String.

Converts JsonValue to String.

given jsonValueToTry[T](using converter: JsonInput[T]): jsonValueToTry[T]

Converts JsonValue to Success or returns Failure if unsuccessful.

Converts JsonValue to Success or returns Failure if unsuccessful.

given leftToJsonValue[T](using converter: JsonOutput[T]): leftToJsonValue[T]

Converts Left to JsonValue.

Converts Left to JsonValue.

Converts Long to JsonNumber.

Converts Long to JsonNumber.

given mapToJsonObject[T, M <: ([T] =>> Map[String, T])](using converter: JsonOutput[T]): mapToJsonObject[T, M]

Converts Map to JsonObject.

Converts Map to JsonObject.

Converts None to JsonNull.

Converts None to JsonNull.

given optionToJsonValue[T, M <: (Option)](using converter: JsonOutput[T]): optionToJsonValue[T, M]

Converts Some to JsonValue or returns JsonNull if None.

Converts Some to JsonValue or returns JsonNull if None.

given rightToJsonValue[T](using converter: JsonOutput[T]): rightToJsonValue[T]

Converts Right to JsonValue.

Converts Right to JsonValue.

Converts Short to JsonNumber.

Converts Short to JsonNumber.

Converts String to JsonString.

Converts String to JsonString.

given toJsonArrayConversion(using converter: JsonInput[JsonArray]): toJsonArrayConversion

Applies conversion using JsonInput[JsonArray].

Applies conversion using JsonInput[JsonArray].

given toJsonObjectConversion(using converter: JsonInput[JsonObject]): toJsonObjectConversion

Applies conversion using JsonInput[JsonObject].

Applies conversion using JsonInput[JsonObject].

given tryToJsonValue[T, M <: (Try)](using converter: JsonOutput[T]): tryToJsonValue[T, M]

Converts Success to JsonValue or returns JsonNull if Failure.

Converts Success to JsonValue or returns JsonNull if Failure.

given tupleToJsonField[T](using converter: JsonOutput[T]): tupleToJsonField[T]

Converts (String, T) to (String, JsonValue).

Converts (String, T) to (String, JsonValue).

Extensions

Extensions

extension (json: JsonValue)
@targetName("at")
def \(name: String): JsonValue

Gets value in JSON object.

Gets value in JSON object.

Value parameters:
name

field name

Throws:
ClassCastException

if not JsonObject

@targetName("at")
def \(index: Int): JsonValue

Gets value in JSON array.

Gets value in JSON array.

Value parameters:
index

array index

Throws:
ClassCastException

if not JsonArray

@targetName("collect")
def \\(name: String): Seq[JsonValue]

Collects values with given field name while traversing nested objects and arrays.

Collects values with given field name while traversing nested objects and arrays.

import grapple.json.{ Json, \\, given }

val json = Json.parse("""{
 "node": {
   "name": "localhost",
   "users": [
     { "id": 0,    "name": "root" },
     { "id": 1000, "name": "lupita"  }
   ]
 }
}""")

val names = (json \\ "name").map(_.as[String])

assert { names == Seq("localhost", "root", "lupita") }
Value parameters:
name

field name