Packages

  • package root

    JSON (JavaScript Object Notation) is a lightweight data-interchange format.

    JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages,

    JSON has only types of string, number, boolean, object, array, and null. This library includes additional types such as date, int, long, double, counter, binary, UUID, ObjectId (as in BSON), etc.

    It is very easy to parse a JSON object:

    val doc =
      json"""
      {
        "store": {
          "book": [
            {
              "category": "reference",
              "author": "Nigel Rees",
              "title": "Sayings of the Century",
              "price": 8.95
            },
            {
              "category": "fiction",
              "author": "Evelyn Waugh",
              "title": "Sword of Honour",
              "price": 12.99
            },
            {
              "category": "fiction",
              "author": "Herman Melville",
              "title": "Moby Dick",
              "isbn": "0-553-21311-3",
              "price": 8.99
            },
            {
              "category": "fiction",
              "author": "J. R. R. Tolkien",
              "title": "The Lord of the Rings",
              "isbn": "0-395-19395-8",
              "price": 22.99
            }
          ],
          "bicycle": {
            "color": "red",
            "price": 19.95
          }
        }
      }
      """

    The interpolator json parse a string to JsObject. To parse an array, use the interpolator jsan to JsArray. It is also okay to embed variable references directly in processed string literals.

    val x = 1
    json"""
      {
        "x": $x
      }
    """

    If the string is not a JSON object but any other valid JSON expression, one may use parseJson method to convert the string to a JsValue.

    "1".parseJson

    The json interpolator can only be applied to string literals. If you want to parse a string variable, the parseJson method can always be employed. If you know the string contains a JSON object, you may also use the method parseJsObject.

    val s = """{"x":1}"""
    s.parseJsObject

    To serialize a JSON value (of type JsValue) in compact mode, you can just use toString. To pretty print, use the method prettyPrint.

    doc.toString
    doc.prettyPrint

    With a JsObject or JsArray, you can refer to the individual elements with a variation of array syntax, like this:

    doc("store")("bicycle")("color")
    doc("store")("book")(0)("author")

    Note that we follow Scala's array access convention by () rather than [] in JavaScript.

    Besides, you can use the dot notation to access its fields/elements just like in JavaScript:

    doc.store.bicycle.color
    doc.store.book(0).author

    It is worth noting that we didn't define the type/schema of the document while Scala is a strong type language. In other words, we have both the type safe features of strong type language and the flexibility of dynamic language in this JSON library.

    If you try to access a non-exist field, JsUndefined is returned.

    scala> doc.book
    res11: unicorn.json.JsValue = undefined

    Although there are already several nice JSON libraries for Scala, the JSON objects are immutable by design, which is a natural choice for a functional language. For database, however, data mutation is necessary. Therefore, JsObject and JsArray are mutable data structures. You can set/add a field just like in JavaScript:

    json.store.bicycle.color = "green"

    To delete a field from JsObject, use remove method:

    doc.store.book(0) remove "price"

    It is same as setting it JsUndefined:

    doc.store.book(0).price = `JsUndefined`

    To delete an element from JsArray, the remove method will effectively remove it from the array. However, setting an element to undefined doesn't reduce the array size.

    // delete the first element and array size is smaller
    doc.store.book.remove(0)
    // set the first element to undefined but array size keeps same
    doc.store.book(0) = JsUndefined

    It is also possible to append an element or another array to JsArray:

    val a = JsArray(1, 2, 3, 4)
    a += 5
    
    a ++= JsArray(5, 6)

    Common iterative operations such as foreach, map, reduce can be applied to JsArray too.

    doc.store.book.asInstanceOf[JsArray].foreach { book =>
     println(book.price)
    }

    Because Scala is a static language, it is impossible to know doc.store.book is an array at compile time. So it is typed as generic JsValue, which is the parent type of specific JSON data types. Therefore, we use asInstanceOf[JsArray] to convert it to JsArray in order to use foreach.

    Definition Classes
    root
  • package smile
    Definition Classes
    root
  • package json

    Definition Classes
    smile
  • CompactPrinter
  • JsArray
  • JsBinary
  • JsBoolean
  • JsCounter
  • JsDate
  • JsDateTime
  • JsDecimal
  • JsDouble
  • JsInt
  • JsLong
  • JsNull
  • JsObject
  • JsObjectId
  • JsString
  • JsTime
  • JsTimestamp
  • JsUUID
  • JsUndefined
  • JsValue
  • JsValueOrdering
  • JsonHelper
  • JsonParser
  • JsonPrinter
  • JsonSerializer
  • ObjectId
  • ParserInput
  • PrettyPrinter

object JsonSerializer

Linear Supertypes
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. JsonSerializer
  2. AnyRef
  3. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. Protected

Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  2. final def ##: Int
    Definition Classes
    AnyRef → Any
  3. final def ==(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  4. val BINARY_SUBTYPE_BINARY_OLD: Byte
  5. val BINARY_SUBTYPE_FUNCTION: Byte
  6. val BINARY_SUBTYPE_GENERIC: Byte

    Binary subtypes

  7. val BINARY_SUBTYPE_MD5: Byte
  8. val BINARY_SUBTYPE_USER_DEFINED: Byte
  9. val BINARY_SUBTYPE_UUID: Byte
  10. val BINARY_SUBTYPE_UUID_OLD: Byte
  11. val END_OF_DOCUMENT: Byte

    End of document

  12. val END_OF_STRING: Byte

    End of string

  13. val FALSE: Byte
  14. val TRUE: Byte
  15. val TYPE_ARRAY: Byte
  16. val TYPE_BIGDECIMAL: Byte
  17. val TYPE_BINARY: Byte
  18. val TYPE_BOOLEAN: Byte
  19. val TYPE_DATE: Byte
  20. val TYPE_DATETIME: Byte
  21. val TYPE_DBPOINTER: Byte
  22. val TYPE_DECIMAL128: Byte
  23. val TYPE_DOCUMENT: Byte
  24. val TYPE_DOUBLE: Byte

    Type markers, based on BSON (http://bsonspec.org/spec.html).

  25. val TYPE_INT32: Byte
  26. val TYPE_INT64: Byte
  27. val TYPE_JAVASCRIPT: Byte
  28. val TYPE_JAVASCRIPT_WITH_SCOPE: Byte
  29. val TYPE_MAXKEY: Byte
  30. val TYPE_MINKEY: Byte
  31. val TYPE_MONGODB_TIMESTAMP: Byte
  32. val TYPE_NULL: Byte
  33. val TYPE_OBJECTID: Byte
  34. val TYPE_REGEX: Byte
  35. val TYPE_STRING: Byte
  36. val TYPE_SYMBOL: Byte
  37. val TYPE_TIME: Byte
  38. val TYPE_TIMESTAMP: Byte
  39. val TYPE_UNDEFINED: Byte
  40. val UTF8: Charset
  41. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  42. implicit def byteBuffer2ArrayByte(buffer: ByteBuffer): Array[Byte]

    Helper function convert ByteBuffer to Array[Byte].

  43. def clone(): AnyRef
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.CloneNotSupportedException]) @native()
  44. final def eq(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  45. def equals(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef → Any
  46. def finalize(): Unit
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.Throwable])
  47. final def getClass(): Class[_ <: AnyRef]
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  48. def hashCode(): Int
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  49. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  50. final def ne(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  51. final def notify(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  52. final def notifyAll(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  53. val null: Array[Byte]
  54. final def synchronized[T0](arg0: => T0): T0
    Definition Classes
    AnyRef
  55. def toString(): String
    Definition Classes
    AnyRef → Any
  56. val undefined: Array[Byte]

    Encoding of "undefined"

  57. final def wait(): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.InterruptedException])
  58. final def wait(arg0: Long, arg1: Int): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.InterruptedException])
  59. final def wait(arg0: Long): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.InterruptedException]) @native()

Inherited from AnyRef

Inherited from Any

Ungrouped