如何在嵌套的json中验证子值

时间:2017-01-13 22:46:03

标签: json command-line jq

这是json回复机构:

{
  "studentName": "good student",
  "age": "18",
  "address": "street 123",
  "courses": {
    "math": {
      "description": "how to calculate",
      "enrollment": "enrolled",
      "status": {
        "result": "OK"
      }
    },
    "english": {
      "description": "abc",
      "enrollment": "not-enrolled",
      "status": {
        "result": "OK"
      }
    }
  }
}

我想验证"注册"例如,我想以格式获得输出:

math : enrolled
english : not-enrolled

想知道如何使用jq命令执行此操作,提前感谢。

2 个答案:

答案 0 :(得分:1)

不确定你的意思"验证。"但要简单地获取"course"及其当前"enrollment"状态,您可以执行以下操作:

.courses | to_entries[] | "\(.key) : \(.value.enrollment)"

答案 1 :(得分:0)

如果"验证"意味着检查值是否符合预期,然后您可以使用这些行中的过滤器:

.courses
| with_entries( select( .value.enrollment as $e
                | ["enrolled", "not-enrolled"] | index($e) | not) )

即选择"注册"不在可接受的值列表中。 (这里," X | not"具有否定X的效果。)

针对您的数据运行此功能,增加了一个"注册"当然是无效的收益率:

{
  "french": {
    "description": "abc",
    "enrollment": "non",
    "status": {
      "result": "OK"
    }
  }
}