0

I'm trying the following:

var objJson = jQuery.parseJSON('"myFunc": function(){ ... }');

This fails. Now my question(s): Why does it fail and how can I achieve what I'm trying?

Thank you in advance!

Dänu
  • 5,791
  • 9
  • 43
  • 56
  • would this work using eval? it's a closed system, so security isn't really a concern. Edit: Put this in an answer and I'll check it ;-) – Dänu Oct 31 '11 at 18:12
  • 2
    I think we need to define *what* you are trying to achieve before we can provide a solution. The string content passed to the `parseJSON` method is malformed, additionally JSON does not convey function definitions so even if it were parsed it would result in an empty object. What is your *goal*? – Quintin Robinson Oct 31 '11 at 18:13
  • 2
    Related: http://stackoverflow.com/questions/2001449/is-it-valid-to-define-functions-in-json-results – Colin Brock Oct 31 '11 at 18:20

2 Answers2

1

You seem to have a misconception about what JSON is. JSON is a simple data format with a syntax that resembles JavaScript objects. It's so simple that spec fits a single page. If you have functions it it, it isn't JSON. Thus there is no point in using JSON tools.

Now, the usual way to inject external JavaScript code into an HTML document is the <script> tag:

<script type="text/javascript" src="/path/to/code.js">
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • +1 because I agree with you. [RFC 4627](http://www.ietf.org/rfc/rfc4627), which described JSON format, contains also nothing about functions. The article about JSON in Wikipedia has special paragraph [unsupported native data types](http://en.wikipedia.org/wiki/JSON#Unsupported_native_data_types) where one can find functions. – Oleg Oct 31 '11 at 21:00
0

ok, the following worked for me (should have googled a bit longer):

var o = eval('(' + '"myFunc": function(){ ... }' + ')')
Dänu
  • 5,791
  • 9
  • 43
  • 56
  • This could never have worked. The surrounding parentheses inside the string should be curly braces: `eval('{' + '"myFunc": function(){ ... }' + '}')` is equivalent to `var o = {myFunc: function(){ ... } }`.` – Rob W Oct 31 '11 at 18:39