选择匹配的子字符串

时间:2019-07-09 17:44:44

标签: jq

给出以下Ideal2.json


[
    {
    "url": "/classroom-videos/lesson1/sublesson1/video",
        "data": {
            "fieldset": "lesson-video-overview",
            "title": "5th Grade Math - Interpreting Fractions",
        },
        "order": 4
    },
    {
    "url": "/classroom-videos/lesson1/sublesson2/video",
        "data": {
            "fieldset": "lesson-video-clip-single",
            "title": "Post-Lesson Debrief Part 5",
        },
        "order": 14
    },
    {
        "url" : "about-us",
        "data": {
            "fieldset": "lesson-video-clip-single",
            "title": "Lesson Part 2B",
        },
        "order": 6
    }
]

我只想提取网址以/classroom-videos/开头的项目

理想情况下,我的输出如下所示:


[
    {
    "url": "/classroom-videos/lesson1/sublesson1/video",
        "data": {
            "fieldset": "lesson-video-overview",
            "title": "5th Grade Math - Interpreting Fractions",
        },
        "order": 4
    },
    {
    "url": "/classroom-videos/lesson1/sublesson2/video",
        "data": {
            "fieldset": "lesson-video-clip-single",
            "title": "Post-Lesson Debrief Part 5",
        },
        "order": 14
    }
]

我没有运气就尝试了很多变化: 例如 select(.url | contains("yomama"))产生 jq:错误(在:47):无法使用字符串“ url”索引数组 退出状态5

.[].url生成一个很好的所有URL列表

2 个答案:

答案 0 :(得分:0)

看起来这可以解决问题:

jq '.[] | select(.url |test("classroom-videos"))'

答案 1 :(得分:0)

或者,使用基于行走路径的unix实用程序 jtc ,可以透明地实现相同的JSON操作:

bash $ <ideal2.json jtc -w'<^/classroom-videos/>R:[-1]' -j
[
   {
      "data": {
         "fieldset": "lesson-video-overview",
         "title": "5th Grade Math - Interpreting Fractions"
      },
      "order": 4,
      "url": "/classroom-videos/lesson1/sublesson1/video"
   },
   {
      "data": {
         "fieldset": "lesson-video-clip-single",
         "title": "Post-Lesson Debrief Part 5"
      },
      "order": 14,
      "url": "/classroom-videos/lesson1/sublesson2/video"
   }
]
  • 第一个步行路径词素(<^/classroom-videos/>R:)递归查找标签与REGEX(后缀R)相匹配的每条记录;找到后,jtc将备份1级(lexeme [-1]),该级别将指向父记录
  • -j将所有找到(遍历)的条目包装到JSON数组中

PS>披露:我是jtc-用于JSON操作的shell cli工具的创建者