[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: |
2QdxY4RzWzUUiLuE |
Subject: |
Re: Parse a field in JSON given a path to the field |
Date: |
Wed, 26 Jan 2022 16:19:36 -0600 |
On 2022-01-26 at 22:05:49 +0000,
Tim Landscheidt <tim@tim-landscheidt.de> wrote:
> Husain Alshehhi <husain@alshehhi.io> wrote:
>
> > 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
> > | )
> > `----
>
> If the path is fixed, you could also use let-alist:
>
> | ELISP> (let ((json (json-parse-string "{\n \"field\": {\n \"field1\":
> {\n \"field2\": {\n \"field3\": \"value\"\n }\n }\n
> }\n}\n"
> | :object-type 'alist)))
> | (let-alist json
> | (message "field/field1/field2/field3 = %S"
> .field.field1.field2.field3)))
> | "field/field1/field2/field3 = \"value\""
> | ELISP>
I wrote this in Common Lisp; it should work (but I haven't tested it) in
Elisp:
(defun json-drill (json keys)
(let ((value json))
(dolist (key keys value)
(setf value (gethash key value)))))
The keys argument is a list of keys rather than a single string with the
keys separated by slashes. Your example would look like this:
(let ((json-data (json-parse json-string)))
(let ((field3 (json-drill json '("field" "field1" "field2" "field3"))))
;; process field3
))
Obviously, whatever you pass to json-drill as keys doesn't have to be a
constant.