使用jq,如何从JSON数据准确地从嵌套数组中获取嵌套值?

时间:2019-09-24 17:31:06

标签: json jq

我有一个看起来像这样的JSON文件:

{
    "people": {
        "names": [{
                "last_name": "Smith",
                "first_names": [{
                        "name": "Bill"
                    },
                    {
                        "name": "Alice"
                    },
                    {
                        "name": "Mary"
                    }
                ]
            },
            {
                "last_name": "Brown",
                "first_names": [{
                        "name": "Gil"
                    },
                    {
                        "name": "Bob"
                    },
                    {
                        "name": "Mary"
                    }
                ]
            },
            {
                "last_name": "Sanchez",
                "first_names": [{
                        "name": "Gil"
                    },
                    {
                        "name": "Jose"
                    },
                    {
                        "name": "Marlena"
                    }
                ]
            }
        ]
    }
}

我正在寻找的输出是:

Smith, Bill
Smith, Alice
Smith, Mary
Brown, Gil
Brown, Bob
Brown, Mary
Sanchez, Gil
Sanchez, Jose
Sanchez, Marlena

我创建了一个jq查询,如下所示:

jq -r '.people | "\(.names[].last_name), \(.names[].first_names[].name)"' nameFile.json | sort

但是我得到的输出是:

Brown, Alice
Brown, Bill
Brown, Bob
Brown, Gil
Brown, Gil
Brown, Jose
Brown, Marlena
Brown, Mary
Brown, Mary
Sanchez, Alice
Sanchez, Bill
Sanchez, Bob
Sanchez, Gil
Sanchez, Gil
Sanchez, Jose
Sanchez, Marlena
Sanchez, Mary
Sanchez, Mary
Smith, Alice
Smith, Bill
Smith, Bob
Smith, Gil
Smith, Gil
Smith, Jose
Smith, Marlena
Smith, Mary
Smith, Mary

显然这是不正确的,我可以看到原因:第二个表达式忠实地遍历了名称数组中的每个匹配项。但是我看不出如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

要获得所需的结果,您必须在url = "http://example.com/foo/baz/../." url = process(url) url = "http://example.com/foo/" 上循环的循环外迭代http://example.com

.names