Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript Object (incl. functions) to String

Tags:

javascript

Hey, Im trying to convert specific javascript objects to a String. So far I'm working with json2.js. As soon as my Object contain functions, those functions are stripped. I need a way to convert functions too, any ideas?

There is a toString() method for functions in firefox, but how to make that work with json2.js?

like image 286
markusf Avatar asked Mar 10 '11 19:03

markusf


People also ask

How do you turn an object into a string in JavaScript?

Stringify a JavaScript Object Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

How do you turn an object into a string?

Convert Object to String in java using toString() method of Object class or String. valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string.

Which of these function is used to convert object to string?

The answer is option D (str(x)). str(x) converts the object to a string in python.

Can a JavaScript object contain a function?

Object properties can be both primitive values, other objects, and functions. An object method is an object property containing a function definition. JavaScript objects are containers for named values, called properties and methods.


2 Answers

Actually, I think it is possible and easy. At least when doing jsonP with nodeJS it works for me just fine, and it's demonstratable by the following fiddle. I did it by simply adding strings to a function:

var anyString = ''; var aFunction = function() { return true; }; var functionToText = anyString + aFunction; console.log(functionToText); 

here's the fiddle: http://jsfiddle.net/itsatony/VUZck/

like image 78
itsatony Avatar answered Sep 24 '22 11:09

itsatony


Use String() function http://www.w3schools.com/jsref/jsref_string.asp

var f = function(a, b){     return a + b;  } var str = String(f); 
like image 23
Milk3dfx Avatar answered Sep 22 '22 11:09

Milk3dfx