help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Parse a field in JSON given a path to the field


From: Andreas Röhler
Subject: Re: Parse a field in JSON given a path to the field
Date: Sat, 13 Nov 2021 14:15:10 +0100
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Thunderbird/78.14.0


Am 11.11.21 um 19:42 schrieb Husain Alshehhi:
Does emacs provide a function that can return a path from a JSON object? I find 
something like this useful if I want a field from a nested, large JSON. Here is 
an example of a JSON string

,----
| {
| "field" : {
|   "field1" : {
|     "field2" : {
|       "field3" : "value"
|     }
|   }
| }
`----

I do something like:

,----
| ;; assume that the value is in json-string
| (let ((json (json-parse json-string))
|       (field (gethash "field" json))
|       (field1 (gethash "field1" field))
|       (field2 (gethash "field2" field1))
|       (field3 (gethash "field3" field2)))
|   ;; process field3
|   )
`----

I wonder if there is something like

,----
| (let ((field3 (json-parse-path "field/field1/field2/field3" json-string)))
|   ;; process field3
|   )
`----



Maybe go on with this, which puts the value into messaging for now.

Idea is to specify the nesting in order to get the value of interest:


(defun getjsonfield (nesting)
  "Get the json-value of the provided nesting."
  (interactive "p")
  (while (< (nth 0 (parse-partial-sexp (point-min) (point))) nesting)
    (down-list))
  (when (looking-at "\\([[:blank:]]*\\)\\([[:print:]]+\\)")
    (goto-char (match-end 2))
    (skip-chars-forward " \t\r\n\f")
    (when (looking-at "\\([[:blank:]]*\\)\\([^: ]+\\)[[:blank:]]*:[[:blank:]]*\\([[:print:]]+\\)")
      (message "%s" (match-string-no-properties 2))
      (message "%s" (match-string-no-properties 3)))))




reply via email to

[Prev in Thread] Current Thread [Next in Thread]