簡體   English   中英

基於鍵和類型的JSON值的條件變換與jq

[英]Conditional transform of JSON value based on key and type with jq

我有一個 json 文件,我想使用jq將一些命名鍵的值從數字( 0 / 1 )轉換為 boolean ( 0 => false , 1 => true )。

轉換應該是可重入的。 如果我在(部分)轉換的文件上運行它,已經轉換的密鑰應該保持不變。

鑒於此 json 文件:

{
  "foo": {
    "bar": {
      "color": "green",
      "visible": 0
    },
    "baz": {
      "fruit": "banana",
      "tasty": true
    }
  },
  "fubar": {
    "string": "hi",
    "value": "world",
    "enabled": 1,
    "sub": {
      "valuable": true,
      "empty": false
    }
  },
  "running": 1
}

以及以下鍵列表:

  • .foo.bar.visible
  • .foo.baz.tasty
  • .fubar.enabled
  • .fubar.sub.empty
  • 。跑步

我希望 jq 將上述內容轉換為:

{
  "foo": {
    "bar": {
      "color": "green",
      "visible": false
    },
    "baz": {
      "fruit": "banana",
      "tasty": true
    }
  },
  "fubar": {
    "string": "hi",
    "value": "world",
    "enabled": true,
    "sub": {
      "valuable": true,
      "empty": false
    }
  },
  "running": true
}

我想出了這個(使用前兩個鍵只是為了保持簡短):

cat in.json | jq '.foo.bar.visible = (if .foo.bar.visible | type == "boolean" then .foo.bar.visible elif .foo.bar.visible == 1 then true else false end) | .foo.baz.tasty = (if .foo.baz.tasty | type == "boolean" then .foo.baz.tasty elif .foo.baz.tasty == 1 then true else false end)' > out.json

但必須有更好的方法嗎?

還嘗試將其放入def中,但沒有奏效:

def numerictobool(key):
  $key = (if $key | type == "boolean" then $key elif $key == 1 then true else false end)
numerictobool(.network.eth0.enabled)
def numerictobool:
  if type == "boolean" then . else . == 1 end;

.
| .foo.bar.visible |= numerictobool
| .foo.baz.tasty |= numerictobool
| .fubar.enabled |= numerictobool
| .fubar.sub.empty |= numerictobool
| .running |= numerictobool

...根據您的輸入發出 output:

{
  "foo": {
    "bar": {
      "color": "green",
      "visible": false
    },
    "baz": {
      "fruit": "banana",
      "tasty": true
    }
  },
  "fubar": {
    "string": "hi",
    "value": "world",
    "enabled": true,
    "sub": {
      "valuable": true,
      "empty": false
    }
  },
  "running": true
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM