Preserving undefined that JSON.stringify otherwise removes

前端 未结 7 1675
长情又很酷
长情又很酷 2020-12-23 18:33

How do I preserve undefined values when doing JSON.stringify(hash)?

Here\'s an example:

var hash = {
  \"name\" : \"boda\",
  \"email\" : undefined,
         


        
相关标签:
7条回答
  • 2020-12-23 19:04

    You can pass a replacer function to JSON.stringify to automatically convert undefined values to null values, like this:

    var string = JSON.stringify(
      obj,
      function(k, v) { return v === undefined ? null : v; }
    );
    

    This works for undefined values inside arrays as well, as JSON.stringify already converts those to null.

    0 讨论(0)
  • 2020-12-23 19:05

    Im reading between the lines here and guessing that you want to have the value undefined when you use JSON.parse?

    If that is the case you could use the following:

    var encodeUndefined = function(obj, undefinedPaths, path) {
      path = path || 'ROOT';
      for (var key in obj) {
        var keyPath = path + '.' + key;
        var value = obj[key];
        if (value === undefined) {
          undefinedPaths.push(keyPath);
        } else if (typeof value == "object" && value !== null) {
          encodeUndefined(obj[key], undefinedPaths, keyPath);
        }
      }
    }
    
    var stringifyAndPreserveUndefined = function(obj) {
      var undefinedPaths = [];
      //save all paths that have are undefined in a array.
      encodeUndefined((obj), undefinedPaths);
      return JSON.stringify({
        ROOT: obj,
        undefinedPaths: undefinedPaths
      }, function(k, v) { if (v === undefined) { return null; } return v; });
    }
    
    var parseAndRestoreUndefined = function(value) {
      var data = JSON.parse(value);
      var undefinedPaths = data.undefinedPaths;
      var obj = data.ROOT;
      //Restore all undefined values
      for (var pathIndex = 0; pathIndex < undefinedPaths.length; pathIndex++) {
        var pathParts = undefinedPaths[pathIndex].substring(5).split('.');
        var item = obj;
        for (var pathPartIndex = 0; pathPartIndex < pathParts.length - 1; pathPartIndex++) {
          item = item[pathParts[pathPartIndex]];
        }
        item[pathParts[pathParts.length - 1]] = undefined;
      }
      return obj;
    }
    
    var input = {
      test1: 'a',
      test2: 'b',
      test3: undefined,
      test4: {
        test1: 'a',
        test2: undefined
      }
    };
    var result = stringifyAndPreserveUndefined(input);
    var result2 = parseAndRestoreUndefined(result);
    

    stringifyAndPreserveUndefined will encode all undefined values in a array and when you call parseAndRestoreUndefined it will put them in the correct place again.

    The one downside is the json will not look exactly like the object. In the example above it will turn into {"ROOT":{"test1":"a","test2":"b","test4":{"test1":"a"}},"undefinedPaths":["ROOT.test3","ROOT.test4.test2"]}

    0 讨论(0)
  • 2020-12-23 19:18

    This should do the trick

    // Since 'JSON.stringify' hides 'undefined', the code bellow is necessary in
    // order to display the real param that have invoked the error.
    JSON.stringify(hash, (k, v) => (v === undefined) ? '__undefined' : v)
        .replace('"__undefined"', 'undefined')
    
    0 讨论(0)
  • 2020-12-23 19:19

    You can preserve the key by converting to null since a valid JSON does not allow undefined;

    Simple one liner:

    JSON.stringify(obj, (k, v) => v === undefined ? null : v)
    
    0 讨论(0)
  • 2020-12-23 19:21

    Use null instead of undefined.

    var hash = {
      "name" : "boda",
      "email" : null,
      "country" : "africa"
    };
    
    var string = JSON.stringify(hash);
    
    > "{"name":"boda","email":null,"country":"africa"}"
    
    0 讨论(0)
  • 2020-12-23 19:21

    This will cause it to print as undefined but this is INVALID json, but is valid JavaScript.

    var string = JSON.stringify(obj, function(k,v){return v===undefined?"::undefined::":v}, 2).replace(new RegExp("\"::undefined::\"", 'g'), "undefined");
    
    0 讨论(0)
提交回复
热议问题