在 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
}

原文由 the_darkside 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 666
2 个回答

感谢您的答复。我刚刚意识到 JSON.stringify() 有一个 REPLACER 参数( 信息在这里

所以我刚刚补充说:

 function replacer(key, value) {
  // Filtering out properties
  if (value === null) {
    return undefined;
  }
  return value;
}

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

原文由 the_darkside 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以这样做:

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

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

原文由 Masoud 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题