Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide null values in output from 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>' 

The result looks something like this:

{   "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  } 

I am new to JS and would like to know if there might be a simple way to completely exclude the columns containing null values - a function that roughly looks like this:

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

So that in the end, the object in the panel looks like this:

{   "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 } 
like image 360
the_darkside Avatar asked Dec 13 '16 07:12

the_darkside


People also ask

Does JSON Stringify remove undefined?

JSON. stringify will omit all object attributes that are undefined .

What does JSON Stringify () method do?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

What is the output of JSON Stringify?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj); The result will be a string following the JSON notation.


1 Answers

You can do something like this:

let x = {    'x1':0,    'x2':null,    'x3':"xyz",     'x4': null  }    console.log(JSON.stringify(x, (key, value) => {    if (value !== null) return value  }))
like image 136
Masoud Avatar answered Sep 18 '22 08:09

Masoud