jq:如何匹配数组之一并获取兄弟值

时间:2017-12-22 10:27:25

标签: json jq

我有一些像这样的JSON:

{
  "x": [
    {
      "name": "Hello",
      "id": "211"
    },
    {
      "name": "Goodbye",
      "id": "221"
    },
    {
      "name": "Christmas",
      "id": "171"
    }
  ],
  "y": "value"
}

使用jq,给定名称值(例如圣诞节),我如何获得它的相关ID(即171)。

我已经能够检查其中一个数组对象中是否存在该名称,但我无法解决如何过滤它的问题

jq -r 'select(.x[].name == "Christmas")'

2 个答案:

答案 0 :(得分:6)

jq 方法:

jq -r '.x[] | select(.name == "Christmas").id' file
171

如果select(boolean_expression)为该输入返回boolean_expression,函数true将使其输入保持不变,否则不会产生输出。

答案 1 :(得分:0)

它也可以像这样完成:

public static DefaultMutableTreeNode getFileStructure(FTPClient client,String workingPath,DefaultMutableTreeNode style )
{

try {

    FTPFile[] files = client.listFiles(workingPath);
    for (FTPFile file : files) {
        if (file.isDirectory())
        {
            DefaultMutableTreeNode fileDirectory =new DefaultMutableTreeNode(file.getName());
           // System.out.println("\n Folder: " +file.toString());
            style.add(fileDirectory);

        //     System.out.println("Node Depth = " + style.getDepth());
            getFileStructure(client, workingPath + "/" + file.getName(),style);
        } else {


        DefaultMutableTreeNode root =new DefaultMutableTreeNode();  

        System.out.println("");
        System.out.println("Working Path: " + workingPath);
        System.out.println("Filename: " + file.getName());

        /// Convert variable (workingPath) to TreePath

        /// Add node to TreePath

        MutableTreeNode node = buildNodeFromString(workingPath);
        MutableTreeNode lastLeaf = node.getLastLeaf();
        TreePath path = new TreePath(lastLeaf.getPath());
        System.out.println("Path =" + path);

        DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)path.getLastPathComponent();





       // style.remove(parentNode);

        MutableTreeNode fileDirectory =new MutableTreeNode(file.getName());
        // parentNode.add(fileDirectory);
        DefaultTreeModel model = (DefaultTreeModel) jt.getModel();
        model.insertNodeInto(fileDirectory,parentNode,parentNode.getChildCount());
       // model.reload(parentNode);

        style.add(parentNode);

        model.reload(style);

        System.out.println("Added to node = " + parentNode.toString());
       // System.out.println("First Node = " + i.getFirstChild().toString());
        //System.out.println("Last Node = " + i.getLastChild().toString());
        System.out.println("Num of Children = " + parentNode.getLeafCount());
        System.out.println("Depth Count= " + style.getDepth());

        //    return i;
        }
    }
} catch (IOException ex) {
    System.out.println("IOException:" + ex);
 } 



 return style;
}

您也可以在链接online jq play

上尝试一下