Is there any possibility to have JSON.stringify preserve functions?

Is there any possibility to have JSON.stringify preserve functions?

json stringify escape quotes
json.stringify pretty
json.stringify replacer
tojson is not a function
json serialize javascript
json stringify object function
react json stringify
json stringify error

Take this object:

x = {
 "key1": "xxx",
 "key2": function(){return this.key1}
}

If I do this:

y = JSON.parse( JSON.stringify(x) );

Then y will return { "key1": "xxx" }. Is there anything one could do to transfer functions via stringify? Creating an object with attached functions is possible with the "ye goode olde eval()", but whats with packing it?


You can't pack functions since the data they close over is not visible to any serializer. Even Mozilla's uneval cannot pack closures properly.

Your best bet, is to use a reviver and a replacer.

https://yuilibrary.com/yui/docs/json/json-freeze-thaw.html

The reviver function passed to JSON.parse is applied to all key:value pairs in the raw parsed object from the deepest keys to the highest level. In our case, this means that the name and discovered properties will be passed through the reviver, and then the object containing those keys will be passed through.

JSON.stringify(), arrays or objects to JSON, although it can also be used with simple data types like strings and numbers. javascript - tojson - Is there any possibility to have JSON.stringify preserve functions? json.stringify replacer (8)


I ran into the same problem, There was another post similar to yours found json-stringify-function. the following may be useful to you:

var JSONfn;
if (!JSONfn) {
    JSONfn = {};
}

(function () {
  JSONfn.stringify = function(obj) {
    return JSON.stringify(obj,function(key, value){
            return (typeof value === 'function' ) ? value.toString() : value;
        });
  }

  JSONfn.parse = function(str) {
    return JSON.parse(str,function(key, value){
        if(typeof value != 'string') return value;
        return ( value.substring(0,8) == 'function') ? eval('('+value+')') : value;
    });
  }
}());

Code Snippet taken from Vadim Kiryukhin's JSONfn.js or see documentation at Home Page

Using JavaScript's JSON.stringify, Take this object: x = { "key1": "xxx", "key2": function(){return this.key1} }. If I do this: y = JSON.parse( JSON.stringify(x) );. Then y will return { "key1": "xxx" }. Is there  Stringify Functions. In JSON, functions are not allowed as object values. The JSON.stringify() function will remove any functions from a JavaScript object, both the key and the value:


Technically this is not JSON, I can also hardly imagine why would you want to do this, but try the following hack:

x.key2 = x.key2.toString();
JSON.stringify(x)  //"{"key1":"xxx","key2":"function (){return this.key1}"}"

Of course the first line can be automated by iterating recursively over the object. Reverse operation is harder - function is only a string, eval will work, but you have to guess whether a given key contains a stringified function code or not.

JSON.stringify(), Let's say we have a complex object, and we'd like to convert it into a string, The method JSON.stringify(student) takes the object and converts it into a string. Fortunately, we can use a function instead of an array as the replacer . as possible: it has a chance to analyze and replace/skip even the whole  The JSON.stringify() method converts a JavaScript object or 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. The source for this interactive example is stored in a GitHub repository.


I've had a similar requirement lately. To be clear, the output looks like JSON but in fact is just javascript.

JSON.stringify works well in most cases, but "fails" with functions.

I got it working with a few tricks:

  1. make use of replacer (2nd parameter of JSON.stringify())
  2. use func.toString() to get the JS code for a function
  3. remember which functions have been stringified and replace them directly in the result

And here's how it looks like:

// our source data
const source = {
    "aaa": 123,
    "bbb": function (c) {
        // do something
        return c + 1;
    }
};

// keep a list of serialized functions
const functions = [];

// json replacer - returns a placeholder for functions
const jsonReplacer = function (key, val) {
    if (typeof val === 'function') {
  	    functions.push(val.toString());
        
        return "{func_" + (functions.length - 1) + "}";
    }
        
    return val;
};

// regex replacer - replaces placeholders with functions
const funcReplacer = function (match, id) {
   return functions[id];
};

const result = JSON
    .stringify(source, jsonReplacer)               // generate json with placeholders
    .replace(/"\{func_(\d+)\}"/g, funcReplacer);   // replace placeholders with functions

// show the result
document.body.innerText = result;
body { white-space: pre-wrap; font-family: monospace; }

Reverse of JSON.stringify?, Since the default implementations of the `JSON.stringify` and `JSON.parse` functions do not. support serialization of Functions have also been left out as the regenerated versions (assuming it is possible to. regenerate them at all) will lose 1) return i;. // or else, push this element, and save the index, to be returned later. Most times it works as expected, while I get an Uncaught TypeError: JSON.stringify is not a function error on certain pages of a website.


This is what I did https://gist.github.com/Lepozepo/3275d686bc56e4fb5d11d27ef330a8ed

function stringifyWithFunctions(object) {
  return JSON.stringify(object, (key, val) => {
    if (typeof val === 'function') {
      return `(${val})`; // make it a string, surround it by parenthesis to ensure we can revive it as an anonymous function
    }
    return val;
  });
};

function parseWithFunctions(obj) {
  return JSON.parse(obj, (k, v) => {
    if (typeof v === 'string' && v.indexOf('function') >= 0) {
      return eval(v);
    }
    return v;
  });
};

Is there any possibility to have JSON.stringify preserve functions?, Stringify your JSON at max speed. Build a stringify() function based on jsonschema. performance, we strongly encourage you to use a fixed schema where possible. toString()) // print a "ready to read" string function, you can save it to a file use the generated string to get back the `stringify` function. The method JSON.stringify(student) takes the object and converts it into a string. The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object. We are ready to send it over the wire or put into a plain data store.


JSON methods, toJSON, Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "​New York" };. Use the JavaScript function JSON.stringify() to convert it into a  What you didn’t know about JSON.Stringify by AbdulFattaah Popoola on February 27, 2017 February 25, 2018 JSON, the ubiquitous data format that has become second nature to engineers all over the world.


Augmented Versions of the `JSON.stringify` & `JSON.parse` functions., A quick refresher about JSON and JavaScript: Not all valid JSON is valid Non-​stringifiable fields get replaced with null in arrays and dropped in objects. The special array handling helps 'preserve' the shape of the array. In the With JavaScript, it would be possible to eval such strings in some scenarios. Check out "Is there any possibility to have JSON.stringify preserve functions?" This answer shows some code that stringifies functions, but that seems like a kind of weird route to go down. Perhaps you could write some methods around each of your objects that converts its state to JSON.


fast-json-stringify, Googling around tells me this isnt possible as JSON.stringify wasn't meant for functions. I am in the process of building a save system for a little game i'm making. I tried altering the stringify method to change even the functions into strings Make an "Item" class with a constructor, that takes a data object as an argument. > JSON.stringify([ function {} ]) '[null]' The toJSON() Method If JSON.stringify() encounters an object that has a toJSON method, it uses that method to obtain a value to be stringified.