jQuery处理空字符串并将其替换为默认值 [英] Jq handling empty strings and replacing them with a default value

查看:108
本文介绍了jQuery处理空字符串并将其替换为默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个要用jq操作的json文件.我能够在大多数情况下显示它的需求.但是,当显示一个空字段的值时,我遇到了一个问题.我正在使用//替代运算符,但未返回所需的输出.用jq处理空字符串的正确方法是什么?

I currently have a json file I am manipulating with jq. I am able to display it how I want for the most part. However, I am running into a problem when displaying values for a field that's empty. I am using the // alternative operator but it is not returning the desired output. What is the right way to handle empty strings with jq?

当前输出:

RELEASE    INSTALLED  LATEST  DEPRECATED
test-app   1.0.0      2.0.0   false
test-app2  3.0.0      true

所需的输出:

RELEASE    INSTALLED  LATEST  DEPRECATED
test-app   1.0.0      2.0.0   false
test-app2  3.0.0      -        true

Jq:

cat test1.json | jq -r 'map({release, installed: .Installed.version, latest: (.Latest.version // "-"), deprecated}) | ( .[0] | keys_unsorted | map(ascii_upcase)), (.[] | [.[]]) | @tsv' | column -t

Json:

[
  {
    "release": "test-app",
    "Installed": {
      "version": "1.0.0",
      "appVersion": ""
    },
    "Latest": {
      "version": "2.0.0",
      "appVersion": ""
    },
    "outdated": true,
    "deprecated": false
  },
  {
    "release": "test-app2",
    "Installed": {
      "version": "3.0.0",
      "appVersion": ""
    },
    "Latest": {
      "version": "",
      "appVersion": ""
    },
    "outdated": false,
    "deprecated": true
  }
]

推荐答案

""并未像Philippe所指出的那样被归类为 null ,但是如果您无法更改json以使" 变为 null ,您可以做的是

"" is not classed as null as Philippe pointed out, but if you're unable to change the json to make the "" become null, what you can do is

jq -r 'map({release, installed: .Installed.version, latest: (if .Latest.version == "" then "-" else .Latest.version end), deprecated}) | ( .[0] | keys_unsorted | map(ascii_upcase)), (.[] | [.[]]) | @tsv' data.json | column -t

这篇关于jQuery处理空字符串并将其替换为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆