复杂的jq过滤器

时间:2014-07-21 21:48:23

标签: json jq

免责声明:这不是家庭作业,这是我正在为工作做的事情的消毒版本。

我试图使用jq过滤一些json数据,并希望为我的过滤器中的每个匹配记录返回一个对象。这里是我正在做的文字说明:"给定一个JSON对象,其中包含学生列表,一些个人信息及其成绩,返回名称,年龄和累积gpa的列表对于在CSC101中获得A的每个学生。"

这是测试JSON对象(程序输入):

{
    "students": [
        {"name": "John", "age": "19", "gender": "m", "from": "Tampa, FL", "cum_gpa": "3.83", "semesters": [
            {"name": "201302", "gpa": "3.67", "grades": {"CSC101": "A", "MAT101": "A", "PSY101": "B"}},
            {"name": "201401", "gpa": "4.00", "grades": {"CSC201": "A", "MAT201": "A", "HIS101": "A"}}
        ]},
        {"name": "Mary", "age": "20", "gender": "f", "from": "Chicago, IL", "cum_gpa": "3.50", "semesters": [
            {"name": "201302", "gpa": "4.00", "grades": {"CSC101": "A", "MAT101": "A", "ECO101": "A"}},
            {"name": "201401", "gpa": "3.00", "grades": {"CSC201": "B", "MAT201": "B", "HUM101": "B"}}
        ]},
        {"name": "Dan", "age": "20", "gender": "m", "from": "Seattle, WA", "cum_gpa": "3.33", "semesters": [
            {"name": "201302", "gpa": "3.33", "grades": {"CHE101": "B", "MAT101": "A", "PSY101": "B"}},
            {"name": "201401", "gpa": "3.33", "grades": {"CHE201": "A", "MAT201": "A", "HUM101": "C"}}
        ]}
    ]
}

这是我当前的过滤器表达式和结果:

cat test.json |jq -c '.students[]|select(.semesters[].grades.CSC101 == "A")|{name: .name, age: .age, gpa: .cum_gpa, CSC101: .semesters[].grades.CSC101}' 
{"name":"John","age":"19","gpa":"3.83","CSC101":"A"}
{"name":"John","age":"19","gpa":"3.83","CSC101":null}
{"name":"Mary","age":"20","gpa":"3.50","CSC101":"A"}
{"name":"Mary","age":"20","gpa":"3.50","CSC101":null}

它有点工作,但它会产生额外的输出。我只想让它产生有CSC101参赛作品的学期,但是它会为所有参加CSC101的学生返回所有学期。有什么建议吗?

1 个答案:

答案 0 :(得分:7)

试试这个过滤器:

.students | map(
    {
        name,
        age,
        gpa: .cum_gpa,
        CSC101: .semesters | map(.grades) | add | .CSC101
    }
    |
    select(.CSC101 == "A")
)

这个想法是为每个学生合并所有学期的所有成绩并获得CSC101成绩。然后筛选出具有A级的学生。

这导致:

[
  {
    "name": "John",
    "age": "19",
    "gpa": "3.83",
    "CSC101": "A"
  },
  {
    "name": "Mary",
    "age": "20",
    "gpa": "3.50",
    "CSC101": "A"
  }
]