javascript - 在 JSON.stringify() 的输出中隐藏空值

标签 javascript json stringify

In my code, all of the info from a Postgres table row are stringified when a specific rowID is selected.

var jsonRes = result.message.rows;

document.getElementById('panel').innerHTML = '<pre>' + JSON.stringify(jsonRes[0], null, "\t") + '</pre>'

结果看起来像这样:

{
  "ogc_fid": 143667,
  "relkey": 288007,
  "acct": "000487000A0010000",
  "recacs": "12.5495 AC",
  "shape_star": 547131.567383,
  "shape_stle": 3518.469618,
  "objectid": 307755,
  "zone_dist": "MU-3",
  "pd_num": null,
  "council_da": null,
  "long_zone_": "MU-3",
  "globalid": "{D5B006E8-716A-421F-A78A-2D71ED1DC118}",
  "ord_num": null,
  "notes": null,
  "res_num": null,
  "effectived": 1345766400000,
  "shape.star": 629707.919922,
  "shape.stle": 3917.657332,
  "case_numbe": null,
  "common_nam": null,
  "districtus": null 
}

我是 JS 的新手,想知道是否有一种简单的方法可以完全排除包含空值的列 - 一个大致如下所示的函数:

function hide(jsonObject) {
    if (property === null) {
      hide property
  } else {
      return str
  }
}

所以最后,面板中的对象看起来像这样:

{
  "ogc_fid": 143667,
  "relkey": 288007,
  "acct": "000487000A0010000",
  "recacs": "12.5495 AC",
  "shape_star": 547131.567383,
  "shape_stle": 3518.469618,
  "objectid": 307755,
  "zone_dist": "MU-3",
  "long_zone_": "MU-3",
  "globalid": "{D5B006E8-716A-421F-A78A-2D71ED1DC118}",
  "effectived": 1345766400000,
  "shape.star": 629707.919922,
  "shape.stle": 3917.657332
}

最佳答案

你可以这样做:

let x = {
  'x1': 0,
  'x2': null,
  'x3': "xyz", 
  'x4': null
}

console.log(JSON.stringify(x, (key, value) => {
  if (value !== null) return value
}))

关于javascript - 在 JSON.stringify() 的输出中隐藏空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41115702/

相关文章:

json - 在 JSON 中格式化 "true"的正确方法是什么?

json.stringify 输出是 1023 个字符......为什么?

javascript - 达到最大长度限制时更改输入字段样式

javascript - this.value 在 Firefox 上有效,但在 Internet Explorer 上无效?

json - 隐藏结构体字段并使其同步字段的访问和修改的最佳方法是什么?

Python 错误 : TypeError: Object of type 'Timestamp' is not JSON serializable'

javascript - NodeJS 和 EJS 的 JSON 字符串化问题

javascript - React 中的 OnClick 事件

javascript - 使用 Javascript 将类添加到 YouTube iframe 元素

java - 为什么在删除 JSON 对象时此循环会过早退出?