【问题标题】:jq: from one json input, construct multiple rows of tsv using an expression against the keys?jq:从一个 json 输入中,使用针对键的表达式构造多行 tsv?
【发布时间】:2021-10-15 03:51:25
【问题描述】:

使用jq我可以通过如下简单的方式提取数据:

find . -name '*.jsonl' | xargs -I {} jq '[.data.Item_A_Foo.value, .data.Item_A_Bar.value] | @tsv' >> foobar.tsv
find . -name '*.jsonl' | xargs -I {} jq '[.data.Item_B_Foo.value, .data.Item_B_Bar.value] | @tsv' >> foobar.tsv
find . -name '*.jsonl' | xargs -I {} jq '[.data.Item_B_Foo.value, .data.Item_B_Bar.value] | @tsv' >> foobar.tsv
...
# and so on

但这似乎很浪费。有没有更高级的使用JQ的方法,或许:

  • 过滤.data.Item_*_Foo.value, .data.Item_*_Bar.value
  • OR 将这些行链接到一个 jq 表达式中(可读性强,紧凑)
# Here is a made up JSON file that can motivate this question. 
# Imagine there are 100,000 of these and they are larger.

{
  "data": 
  {
    "Item_A_Foo": {
       "adj": "wild",
       "adv": "unruly",
       "value": "unknown"
    },
    "Item_A_Bar": {
       "adj": "rotund",
       "quality": "mighty",
       "value": "swing"
    },
    "Item_B_Foo": {
       "adj": "nice",
       "adv": "heroically",
       "value": "medium"
    },
    ... etc. for many Foo's and Bar's of A, B, C, ..., Z types
    "Not_an_Item": {
      "value": "doesn't matter"
    }
}

目标是:

unknown, swing # data.Item_A_Foo.value, data.Item_A_Bar.value
medium, hit # data.Item_B_Foo.value, data.Item_B_Bar.value
whatever, etc. # data.Item_C_Foo.value, data.Item_C_Bar.value

【问题讨论】:

  • 如果您将JSON sn-p(示例)与您的实际结构共享会更容易,以便人们可以更好地提供建议

标签: json dynamic key jq


【解决方案1】:

您的要求细节尚不清楚,但您可以按照此 jq 过滤器建议的方式进行操作:

  .data
  | (keys_unsorted|map(select(test("^Item_[^_]*_Foo$")))) as $foos
  | ($foos | map(sub("_Foo$"; "_Bar"))) as $bars
  | [ .[$foos[]].value, .[$bars[]].value]
  | @tsv

这个想法是动态确定选择哪些键。

【讨论】:

  • 我认为这给了我足够的语法来获得答案。我有一种感觉 jq 很快就会“点击”,但我不太明白为什么事情能正常工作,而 atm 不能工作。
  • @Chris - 关于“点击” - 我很想知道我写的简短介绍 (github.com/pkoppstein/jq/wiki/…) 是否有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 2021-05-13
  • 1970-01-01
相关资源
最近更新 更多