Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects JavaScript Object Notation

Functions in JSON

It's possible pass a function in JSON?

3 Answers

Andrew Robinson
Andrew Robinson
16,372 Points

Certainly is possible: http://stackoverflow.com/questions/3946958/pass-function-in-json-and-execute

Looks like using the function constructor you could pass the part of the JSON into that and create a working function from it.

Just out of curiosity what would be the reason for passing a function in JSON?

It's a little bit complicated. I created a grunt task for upload files to S3 server, and I a need that those files all the time that I run the task are load in a random name folder, so I created a function for create a random string and I need pass that function on the property that the grunt plugin provided me and the only way that I found to do that is pass a function inside a JSON and the read the JSON.

Andrew Robinson
Andrew Robinson
16,372 Points

Ah right okay, I haven't gotten round to grunt yet but it seems like what you're doing will work, hope it all goes smoothly!