Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

JQ - Fetch all the paths in json including "null" values

I have a json file in which I wish to retrieve all the paths of all the keys. I have been using JQ, however, it does not show the paths which have null as their values. What am I missing here?

Json :

{
    "Root": [
        {
            "id1": "val",
            "id2": "val",
            "id3": null,
            "id4": 1,
            "id5": null,
            "id6": "val",
            "id7": {
                "id8": "val",
                "id9": "val",
                "id10": null,
                "id11": "val"
            }
        }
    ]
}
jq -r 'paths(scalars)  as $p  | [ ( [ $p[] | tostring ]  | join(".") ), ( getpath($p) | tojson )] | join(": ")' test_data.json

Output is as shown as

{
    "Root": [
        {
            "id1": "val",
            "id2": "val",
            "id3": null,
            "id4": 1,
            "id5": null,
            "id6": "val",
            "id7": {
                "id8": "val",
                "id9": "val",
                "id10": null,
                "id11": "val"
            }
        }
    ]
}

I wish to see path of the all nodes including those which have null as their value.

question from:https://stackoverflow.com/questions/65947125/jq-fetch-all-the-paths-in-json-including-null-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This issue is covered in the jq FAQ, wherein the following def for a more inclusive version of paths is given:

def allpaths:
  def conditional_recurse(f):  def r: ., (select(.!=null) | f | r); r;
  path(conditional_recurse(.[]?)) | select(length > 0);

The corresponding version of paths/1 would be:

def allpaths(filter):
  allpaths as $p | getpath($p) as $v | select($v | filter) | $p;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...