3

Is it possible? I need to stringify js object with function expressions with all value types on other fields to be not changed.

Example:

I have such javascript object -

var obj = {
    propText: "some text",
    propBool: true,
    propNum: 12345,
    method: function () {
       // some logic here
    }
};

Unfortunately if I'll use JSON.stringify(obj); it will return string without method..

Then I can use replacer function like this:

JSON.stringify(obj, function (key, val) {
  if (typeof val === 'function') {
    return '' + val;
  }
  return val;
});

which will bring me string with functions like strings inside like "function () { ... }"..

Another option I've tried is more complex but result is still a bit not acceptable - use custom stringify function that will wrap JSON.stringify and then replace placeholders in strings

var stringify = function (obj, prop) {
  var placeholder = '____PLACEHOLDER____';
  var fns = [];
  var json = JSON.stringify(obj, function(key, value) {
    if (typeof value === 'function') {
      fns.push(value);
      return placeholder;
    }
    return value;
  });
  json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function(_) {
    return fns.shift();
  });
  return json;
};

but this function is not acceptable for example if you pass another values:

JSON.stringify(22); // outputs 22 typeof number
stringify(22); // outputs 22 typeof function because of .replace() :(

I want my stringified object to look like:

'{
    "propText": "some text",
    "propBool": true,
    "propNum": 12345,
    "method": function () { ... }
}'
Kosmetika
  • 20,774
  • 37
  • 108
  • 172

0 Answers0