简体   繁体   English

基于键和类型的JSON值的条件变换与jq

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

I have a json file where I'd like to transform the value of some named keys from numeric ( 0 / 1 ) to boolean ( 0 => false , 1 => true ) using jq .我有一个 json 文件,我想使用jq将一些命名键的值从数字( 0 / 1 )转换为 boolean ( 0 => false , 1 => true )。

The transform should be re-entrant.转换应该是可重入的。 If I run it on a (partially) transformed file, already converted keys should stay the same.如果我在(部分)转换的文件上运行它,已经转换的密钥应该保持不变。

Given this json file:鉴于此 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
}

and the following list of keys:以及以下键列表:

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

I'd like jq to transform the above into this:我希望 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
}

I've come up with this (using the first two keys only to keep it short):我想出了这个(使用前两个键只是为了保持简短):

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

but there has to be a better way?但必须有更好的方法吗?

Also tried to put it into a def but that didn't work:还尝试将其放入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

...emits as output, given your input: ...根据您的输入发出 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