Home > Back-end >  How to read a JSON file using cl-json (common lisp library) and convert the content to a string?
How to read a JSON file using cl-json (common lisp library) and convert the content to a string?

Time:06-01

I am using Common Lisp, SBCL, Emacs, and Slime.

In SLIME's REPL, I have a variable holding the file location:

CL-USER> json-file
#P"/home/pedro/lisp/json-example.json"

The content of the file is:

{"keyOne": "valueOne"}

I would like to read the data inside the file and return a string:

"{"keyOne": "valueOne"}"

How can I do it? Is it possible to do it with cl-json famous library?

The documentation was terse/hard. It is not good on providing examples. I couldn't find how to do it.

CodePudding user response:

From what I read from the documentation, the API is built around streams. The function json:decode-json is taking a stream in parameter and return an association list which is very convenient to use.

To extract a value from the key, you can use the function (assoc :key-1 assoc-list). It will return a cons with (key . value). To get the value, you need to use the cdr function.

(defparameter json-string "{\"key-1\": \"value-1\"}")

(with-input-from-string (json-stream json-string)
  (let ((lisp-data (json:decode-json json-stream)))
    (cdr (assoc :key-1 lisp-data))))

Obviously, if you have the data in a file you could directly use the stream:

(with-open-file (json-stream "myfile.json" :direction :input)
  (let ((lisp-data (json:decode-json json-stream)))
    (cdr (assoc :key-1 lisp-data))))

Edit due to the comment of OP

The content of the file is:

{"keyOne": "valueOne"}
I would like to read the data inside the file and return a string:
"{"keyOne": "valueOne"}"

This question seems completely unrelated to the JSON library, but anyhow, if one need to open a file and put its content into a string, he can use a function from uiop.

* (uiop:read-file-string "test.txt")
"{\"keyOne\": \"valueOne\"}"

uiop is a library shipped with ASDF, so it's probably available to most Common Lisp's distributions. It's a kind of de-facto standard library and have a lot of interesting functions.

I have done the test on my computer, it's seems to work. I can certify that no data was harmed during that test.

  • Related