Writing a JSON string from a common lisp data structure

Viewed 82

I am trying to create a Common Lisp data structure to output some nested JSON like so:

{
  "array_of_objects": {
    "item1": {
      "foo": {
        "value": "x"
      }
    },
    "item2": {
      "bar": {
        "value": "y"
      }
    }
  },
  "object": {
    "lorem": {
      "foo": "bar"
    }
  }
}

I've chosen the YASON library in order to do this, and started with this example:

(yason:with-output (*standard-output*)
           (yason:with-object ()
             (yason:encode-object-element "hello" "hu hu")
             (yason:with-object-element ("harr")
               (yason:with-array ()
                 (dotimes (i 3)
                   (yason:encode-array-element i))))))

However, I'm not familiar enough with lisp and lisp hash map data structures to truly understand how this works.

What's the most "lispy" way to represent the JSON posted and then output it to stdout. Happy to use any library needed if its quicklisp compatible.

1 Answers

What do you start with? If you want a data structure that will output this JSON, you need hash-tables inside hash-tables. Here's the Cookbook: https://lispcookbook.github.io/cl-cookbook/data-structures.html#hash-table

Below I use serapeum's dict, a literal way to represent hash-tables, and more concise in our case:

(defparameter ht (dict "array_of_objects"
                    (dict "item1"
                       (dict "foo"
                          (dict "value" "x")))))
                       

and I create the JSON with jonathan:

(jojo:to-json ht)
"{\"array_of_objects\":{\"item1\":{\"foo\":{\"value\":\"x\"}}}}"
Related