Demo entry 6636341

elisp

   

Submitted by anonymous on Aug 23, 2017 at 18:39
Language: EmacsLisp. Code size: 1.2 kB.

;; incomplete portion of a json tokenizer/decoder

(defun json-decode-1 (str)
  "Decode JSON contained in STRING into an Elisp object.
This tries to walk backwards through the tokens, pushing the last
non-terminal (object or array) onto a stack.
\n(fn STRING)"
  (let ((tokens (json-tokenize str))
        stack i tok)
    (setq i (1- (length tokens)))
    ;; Skip uninitialized tokens
    (while (null (aref (aref tokens i) 1))
      (cl-decf i))
    (while (>= i 0)
      (setq tok (aref tokens i))
      (pcase (aref tok 1)
       (`string
        (push (substring str (aref tok 2) (aref tok 3)) stack))
       (`array
        (let ((count (aref tok 4))
              res)
          (while (> count 0)
            (push (pop stack) res)
            (cl-decf count))
          (push (vconcat (nreverse res)) stack)))
       (`object
        (let ((count (aref tok 4))
              key val res)
          (while (> count 0)
            (setq key (pop stack))
            (setq val (pop stack))
            (push (cons (intern key) val) res)
            (cl-decf count 2))
          (push res stack))))
      (cl-decf i))
    (car-safe stack)))

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).