Any idea how to find easily values of (deeply) nested keys, when the keys not always exist? #31
-
I have a JSON file like this:
I need to extract the values to the
This works, but feels pretty cumbersome. Is there a way to gather the values easier then with my approach? Also it would be nice if I didn't need to know how deep my |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Your solution works, but I agree it might be nicer to do it without a cat data.json | jello -c '\
res = []
for s in _.details.sections:
for f in s.fields:
if "v" in f:
res.append(f.v)
res' The output should be: ["Yes!","Indeed!"] To find the keys no matter how deep they are, you may need to use a recursive method. Fortunately, the $ cat data.json | jello -s | grep ".v ="
.details.sections[0].fields[0].v = "Yes!";
.details.sections[1].fields[0].v = "Indeed!"; Then you would use normal text utilities ( $ cat data.json | jello -c '\
res = []
res.append(_.details.sections[0].fields[0].v)
res.append(_.details.sections[1].fields[0].v)
res' ["Yes!","Indeed!"] Happy JSON filtering! |
Beta Was this translation helpful? Give feedback.
Your solution works, but I agree it might be nicer to do it without a
try
/except
block. One thing you can do when you don't know if a key exists is to use thein
operator on the dictionary. It would look something like this:The output should be:
To find the keys no matter how deep they are, you may need to use a recursive method. Fortunately, the
-s
option injello
happens to be a recursive function, so you can sort of hack a solution using-s
withgrep
: