Cheshire Documentation

repository·master·Indexed 23 days ago

https://github.com/dakrone/cheshire

A high-performance JSON encoding and decoding library for Clojure built on top of Jackson. Cheshire provides support for Clojure-specific types such as Dates, UUIDs, Sets, and Symbols, as well as SMILE binary format support. It includes APIs for string and stream processing, custom Java class encoders, and experimental large field encoding for streamy JSON.

Tokens
2.1K
Snippets
7
Records
8
Agent score
32%

What's inside Cheshire

  1. Configure arbitrary precision for decoded values

    master
    By default, Cheshire uses BigInteger for non-floating-point numbers and Double for floating-point numbers. To force the use of BigDecimal for floating-point numbers, bind the *use-bigdecimals?* symbol to true within a binding block.
  2. Install Cheshire

    master

    Add Cheshire as a dependency to your project. Cheshire v6.2.0 uses Jackson 2.21.1.

    [cheshire "6.2.0"]

    In your namespace declaration, require cheshire.core to access the primary API:

    (ns my.ns
      (:require [cheshire.core :refer :all]))
    [cheshire "6.2.0"]
  3. Use experimental large field encoding

    master

    The cheshire.experimental namespace contains encode-large-field-in-map, which is designed for streamy JSON encoding. It allows you to encode a map where one of the fields is a large input stream, preventing the entire map from needing to be in memory at once.

    Note: This is experimental and based on Tigris.

    (use 'cheshire.experimental)
    (use 'clojure.java.io)
    
    (println (slurp (encode-large-field-in-map {:id "10"
                                                     :things [1 2 3]
                                                     :body "I'll be removed"}
                                                    :body
                                                    (input-stream (file "/tmp/foo")))))
  4. Add custom encoders for Java classes

    master

    Since version 5.0.0, custom encoding is part of the core namespace. You can register custom encoders for specific Java classes to control how they are serialized. This allows you to use the fast core encoder while providing custom logic for specific types.

    Use add-encoder to register a function that takes the object and a jsonGenerator. Use remove-encoder to unregister them.

    Common built-in encoder helpers include: encode-nil, encode-number, encode-seq, encode-date, encode-bool, encode-named, encode-map, encode-symbol, and encode-ratio.

    (ns myns
      (:require [cheshire.core :refer :all]
                [cheshire.generate :refer [add-encoder encode-str remove-encoder]]))
    
    ;; Add a custom encoder for a class
    (add-encoder java.awt.Color
                 (fn [c jsonGenerator]
                   (.writeString jsonGenerator (str c))))
    
    ;; Use a helper for common encoding actions
    (add-encoder java.net.URL encode-str)
    
    ;; Use the encoder
    (encode (java.awt.Color. 1 2 3))
    
    ;; Remove a custom encoder
    (remove-encoder java.awt.Color)
  5. Encode data to a stream or SMILE

    master

    Cheshire provides methods for writing JSON directly to a stream or using the SMILE binary format.

    • generate-stream: Writes JSON to a Java Writer or OutputStream.
    • generate-smile: Generates SMILE format instead of JSON.
    ;; write some json to a stream
    (generate-stream {:foo "bar" :baz 5} (clojure.java.io/writer "/tmp/foo"))
    
    ;; generate some SMILE
    (generate-smile {:foo "bar" :baz 5})
  6. Decode JSON strings and streams

    master

    Use parse-string (or the alias decode) to convert JSON strings into Clojure data structures.

    Key features:

    • Keywords: Pass true as the second argument to return keys as keywords.
    • Custom Keyword Coercion: Pass a function as the second argument to munge keywords during parsing.
    • Type Specification: In version 2.0.4+, you can pass a function as the third argument to specify how certain fields should be decoded (e.g., converting a JSON array into a Clojure set).

    For streams and SMILE, use parse-stream, parsed-seq (lazy), parse-smile, or parsed-smile-seq (lazy SMILE).

    ;; parse some json
    (parse-string "{\"foo\":\"bar\"}")
    
    ;; parse some json and get keywords back
    (parse-string "{\"foo\":\"bar\"}" true)
    
    ;; parse some json and munge keywords with a custom function
    (parse-string "{\"foo\":\"bar\"}" (fn [k] (keyword (.toUpperCase k))))
    
    ;; parse a stream (keywords option also supported)
    (parse-stream (clojure.java.io/reader "/tmp/foo"))
    
    ;; parse a stream lazily (keywords option also supported)
    (parsed-seq (clojure.java.io/reader "/tmp/foo"))
    
    ;; In 2.0.4 and up, specify return types via a function
    (decode "{\"myarray\":[2,3,3,2],\"myset\":[1,2,2,1]}" true
            (fn [field-name]
              (if (= field-name "myset")
                #{} 
                [])))
    ;; => {:myarray [2 3 3 2], :myset #{1 2}}
  7. Customize JSON factory options

    master

    You can use a custom factory to configure low-level Jackson settings, such as allowing non-numeric numbers (e.g., NaN). This is done by binding factory/*json-factory* using factory/make-json-factory.

    (ns myns
      (:require [cheshire.core :as core]
                [cheshire.factory :as factory]))
    
    (binding [factory/*json-factory* (factory/make-json-factory
                                      {:allow-non-numeric-numbers true})]
      (json/decode "{\"foo\":NaN}" true))
  8. Encode Clojure data to JSON

    master

    Use generate-string (or the alias encode) to convert Clojure data structures into a JSON string. Cheshire supports strings, lists, vectors, sets, maps, symbols, booleans, keywords, and various number types.

    Common options for generate-string include:

    • :pretty: Boolean. If true, enables pretty-printing.
    • :date-format: String. Customizes the date format (default is yyyy-MM-dd'T'HH:mm:ss'Z').
    • :escape-non-ascii: Boolean. If true, escapes non-ASCII characters (e.g., UTF-8).
    • :key-fn: Function. A function used to munge keys during encoding.

    If encoding fails, a JsonGenerationException is thrown.

    ;; generate some json
    (generate-string {:foo "bar" :baz 5})
    
    ;; generate some JSON with Dates with custom Date encoding
    (generate-string {:baz (java.util.Date. 0)} {:date-format "yyyy-MM-dd"})
    
    ;; generate some JSON with pretty formatting
    (generate-string {:foo "bar" :baz {:eggplant [1 2 3]}} {:pretty true})
    
    ;; generate JSON escaping UTF-8
    (generate-string {:foo "It costs £100"} {:escape-non-ascii true})
    
    ;; generate JSON and munge keys with a custom function
    (generate-string {:foo "bar"} {:key-fn (fn [k] (.toUpperCase (name k)))})