Skip to content

Commit

Permalink
Merge pull request Chobbes#52 from egh/json-ld-fix-some-bad-json
Browse files Browse the repository at this point in the history
Json ld fix some bad json
  • Loading branch information
Chobbes authored Jul 29, 2020
2 parents 77f97ad + e2a1b9b commit 5b461ed
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions org-chef-json-ld.el
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@
(require 'json)
(require 'cl-seq)

(defcustom org-chef-json-ld-debug nil
"Debug JSON-LD parsing. Surfaces errors in JSON parsing."
:type 'boolean)

(defun org-chef-json-ld-extract-directions (nodes)
"Get the directions for a recipe from a list of json NODES."
(cond ((stringp nodes)
Expand Down Expand Up @@ -76,8 +80,9 @@
(defun org-chef-json-ld-clean-json (json)
"Clean JSON string of common errors."
(let* ((cleaned-1 (replace-regexp-in-string "\n" " " json))
(cleaned-2 (replace-regexp-in-string "\r" " " cleaned-1)))
cleaned-2))
(cleaned-2 (replace-regexp-in-string "\r" " " cleaned-1))
(cleaned-3 (replace-regexp-in-string "\t" " " cleaned-2)))
cleaned-3))

(defun org-chef-json-ld-extract-recipe (json)
"Find the Recipe LD in JSON and return the hash. Return nil if not found."
Expand All @@ -91,12 +96,22 @@
(cl-some #'org-chef-json-ld-extract-recipe json))
(t nil)))

(defun org-chef-json-ld-safe-read-from-string (str)
"Safely parse STR as json.
Like `json-read-from-string', but catch errors and return nil if
`org-chef-json-ld-debug' is not t."
(if org-chef-json-ld-debug
(json-read-from-string str)
(ignore-errors
(json-read-from-string str))))

(defun org-chef-json-ld-extract-json-ld (dom)
"Extract a list of the json-ld elements in DOM."
(let* ((json-lds (dom-elements dom 'type "^application/ld\\+json$"))
(json-lds-raw (mapcar #'dom-text json-lds))
(json-lds-cleaned (mapcar #'org-chef-json-ld-clean-json json-lds-raw))
(json-lds (mapcar #'json-read-from-string json-lds-cleaned)))
(json-lds (cl-delete-if #'null (mapcar #'org-chef-json-ld-safe-read-from-string json-lds-cleaned))))
json-lds))

(defun org-chef-json-ld-fetch (url)
Expand Down

0 comments on commit 5b461ed

Please sign in to comment.