用 jq 操作 JSON 文件

jq 用一陣子了 (因為配合著 AWS 官方的 AWS Command Line Interface 一起用),剛好看到有人介紹:「jq is sed for JSON」。

現在 Ubuntu 的 package repository 內都有 jq 了 (Ubuntu – Package Search Results -- jq),雖然版本舊了一點,不過基本功能都穩定了,除非有特別的需求,不然應該夠用。

照原文章的範例,假設 1.json 是這樣:

[
  {
    "type": "message",
    "user": "U024HFHU5",
    "text": "hey there",
    "ts": "1385407681.000003"
  },
  {
    "type": "message",
    "user": "U024HGJ4E",
    "text": "right back at you",
    "ts": "1385407706.000006"
  }
]

而你下這樣的 command 就可以抽出來:

$ jq "[.[] | { the_user: .user, the_text: .text }]" 1.json
[
  {
    "the_user": "U024HFHU5",
    "the_text": "hey there"
  },
  {
    "the_user": "U024HGJ4E",
    "the_text": "right back at you"
  }
]

很好用的工具 :o

This entry was posted in Computer, Murmuring, Software and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *