http://www.perlmonks.org?node_id=756287

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi there monks,
I'm looking for a module on CPAN that can convert Javascript code snippets to JSON, apart from also doing the more common data-structure to JSON conversion. I've tried JSON::XS, ::Syck, ::PP and neither seem to be able to do this:

my $data = { age=>18, handler=>\"function(){ alert('hello, worldly') }" }; my $json = encode_json( $data )
And the output should look like this:
{ age: 18, handler: function(){ ... } }

But it usually converts it to: ...handler: "function(...)"

I know I've seen something that can do that somewhere. I think the usual implementation would use scalar references (ie \"function(){ }") to achieve this. But none of the regular JSON modules seem to accept it.

Any clues?
Thanks,
miguel

Replies are listed 'Best First'.
Re: Javascript in your JSON
by derby (Abbot) on Apr 08, 2009 at 12:09 UTC
      I agree that putting scripts in a JSON structure is definitely not in the JSON standard. Even though JSON, before being a data-exchange standard, was just the run-of-the-mill javascript object notation in which script coderefs are perfectly acceptable.

      The thing is that most ajax based frameworks, such as ExtJS, accept, or even recommend putting scripts in a JSON structure. So I guess I'll keep looking for a module that can dump that... or write my own.
      cheers,
      -- miguel

        A JSON file that includes arbitrary JavaScript code is not a JSON file, it's a JavaScript file. You should be looking for tools to help you generate JavaScript, not JSON.

        I think it's really easy to confuse/conflate Javascript object literal notation with JSON - they're not the same thing.

        -derby

        Update: hmmm ... well that was vague. JSON is a subset of Javascript object literal notation that's used for *DATA* exchange. That's why if want to pass around function definitions in JSON, you'll need to de-stringify them - basically subverting the concept of JSON being just for *DATA* exchange.

Re: Javascript in your JSON
by Anonymous Monk on Apr 08, 2009 at 10:02 UTC
    Any clues?
    You're out of luck because thats not JSON, that is javascript
Re: Javascript in your JSON
by Anonymous Monk on Apr 09, 2009 at 09:46 UTC
    As I said, I totally agree that is not JSON, as JSON is a standard per json.org which does not include scripting.

    But I never implied that scripting was part of the JSON standard. I was just looking for a way to augment my JSON structure with scripting.

    For the record, I've just found this simple but effective module, JavaScript::Dumper. It's based on JSON::PP and that does the trick.
    cheers
    -miguel