如何使用jq解析json对象的数组

时间:2018-05-09 11:16:41

标签: json parsing jq

我需要解析一个有很多数组的Json文件。

这是json来源:

{
"iabVersion": "IAB_V2",
"categories": [{
    "categories": [{
        "categories": [{
            "id": "1.1.1",
            "name": "Commercial Trucks"
        },
        {
            "id": "1.1.2",
            "name": "Convertible"
        },
        {
            "id": "1.1.3",
            "name": "Coupe"
        },
        {
            "id": "1.1.4",
            "name": "Crossover"
        },
        {
            "id": "1.1.5",
            "name": "Hatchback"
        },
        {
            "id": "1.1.6",
            "name": "Microcar"
        },
        {
            "id": "1.1.7",
            "name": "Minivan"
        },
        {
            "id": "1.1.8",
            "name": "Off-Road Vehicles"
        },
        {
            "id": "1.1.9",
            "name": "Pickup Trucks"
        },
        {
            "id": "1.1.10",
            "name": "Sedan"
        },
        {
            "id": "1.1.11",
            "name": "Station Wagon"
        },
        {
            "id": "1.1.12",
            "name": "SUV"
        },
        {
            "id": "1.1.13",
            "name": "Van"
        }],
        "id": "1.1",
        "name": "Auto Body Styles"
    }
  }
}

这是需要的json:

{
"id": "1.1.1",
"name": "Commercial Trucks"
}
{
"id": "1.1.2",
"name": "Convertible"
}

如何通过jq解析它?

10倍:)

2 个答案:

答案 0 :(得分:0)

假设您通过关闭这样的数组来修复格式错误的JSON数据:

          ...
          "id": "1.1",
          "name": "Auto Body Styles"
        }
      ]
    }
  ]
}

您可以使用以下jq脚本:

$ jq '.categories[0].categories[0].categories[0],.categories[0].categories[0].categories[1]' file
{
  "id": "1.1.1",
  "name": "Commercial Trucks"
}
{
  "id": "1.1.2",
  "name": "Convertible"
}

jq语句选择这些嵌套数组中的第一个和第二个数组元素。

答案 1 :(得分:0)

假设JSON输入已得到纠正,以下jq过滤器似乎符合要求,例如:

.categories[].categories[].categories[]

这会产生一个JSON对象流,开始于:

{
  "id": "1.1.1",
  "name": "Commercial Trucks"
}
{
  "id": "1.1.2",
  "name": "Convertible"
}