最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Parse JSON string to JavaScript object with function name - Stack Overflow

programmeradmin1浏览0评论

I have a JSON string stored in a data attribute.

{
    "active": true,
    "icons": {
        "activeHeader": "ui-icon-alert"
    },
    "animate": {
        "duration": 1000,
        "always": dMethod
    }
}

And I have a function which named dMethod:

function dMethod() {
  alert("DONE");
} 

When I try to parse the string via JSON.parse I get an error said invalid character. I check and the dMethod is defined when the parse method was running and if I removed the ,"always":dMethod part then the parser worked correctly. I can't use quotation marks around the dMethod because then the type will be string type instead of object function.
Any help would be appreciated.
Thanks,
Péter
EDIT:
Thanks you for all the answers. I make some clarification so maybe better you understand the problem. I make a really simple js library to make jqueryui unobstructive:

var juiObjects = ["accordion", "autoplete", "button", "datepicker", "dialog", "menu", "progressbar", "slider", "spinner", "tabs", "tooltip"];

$(document).ready(function() {
  for (var i = 0; i < juiObjects.length; i++) {
    var attributeName = "data-" + juiObjects[i];
    $("["+ attributeName + "]").each(function () {
      var optionsValue = $(this).attr(attributeName);
      var options = JSON.parse(optionsValue);
      $(this)[juiObjects[i]](options);
    });
  }
});

I had to choice between JSON.parse and eval. But I think eval wouldn't be so good choice. And try to keep the "library" as simple as possible. But it looks like I have sparete the code along the widgets.

I have a JSON string stored in a data attribute.

{
    "active": true,
    "icons": {
        "activeHeader": "ui-icon-alert"
    },
    "animate": {
        "duration": 1000,
        "always": dMethod
    }
}

And I have a function which named dMethod:

function dMethod() {
  alert("DONE");
} 

When I try to parse the string via JSON.parse I get an error said invalid character. I check and the dMethod is defined when the parse method was running and if I removed the ,"always":dMethod part then the parser worked correctly. I can't use quotation marks around the dMethod because then the type will be string type instead of object function.
Any help would be appreciated.
Thanks,
Péter
EDIT:
Thanks you for all the answers. I make some clarification so maybe better you understand the problem. I make a really simple js library to make jqueryui unobstructive:

var juiObjects = ["accordion", "autoplete", "button", "datepicker", "dialog", "menu", "progressbar", "slider", "spinner", "tabs", "tooltip"];

$(document).ready(function() {
  for (var i = 0; i < juiObjects.length; i++) {
    var attributeName = "data-" + juiObjects[i];
    $("["+ attributeName + "]").each(function () {
      var optionsValue = $(this).attr(attributeName);
      var options = JSON.parse(optionsValue);
      $(this)[juiObjects[i]](options);
    });
  }
});

I had to choice between JSON.parse and eval. But I think eval wouldn't be so good choice. And try to keep the "library" as simple as possible. But it looks like I have sparete the code along the widgets.

Share Improve this question edited Aug 12, 2013 at 10:58 Péter asked Aug 12, 2013 at 10:22 PéterPéter 2,1813 gold badges21 silver badges31 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 1

Functions are not valid data types in JSON (see http://en.wikipedia/wiki/JSON#Data_types.2C_syntax_and_example).

I think you have to deserialize it as a string, then post-process your object and set "always" to your method.

It can be done by quoting the dMethod, by executing the function on the window object using the [] syntax:

function dMethod() {
  alert("DONE");
}

var json = '{"active":true,"icons":{"activeHeader":"ui-icon-alert"},"animate":{"duration":1000,"always":"dMethod"}}'; // quoted

var obj = JSON.parse(json);
window[obj.animate.always]();

JSON.parse expects a valid JSON string. So, if you want to use it you should quote the dMethod function. Isn't it possible to replace the string "dMethod" with the real function after the parsing.

You can't parse that string as JSON, because it's not valid JSON.

You can turn the string into an object by executing it using the eval function, but of course the usual warnings about executing anything dynamically applies. If you don't have full control over what's in the string, it might be possible to use for cross site scripting.

var obj = eval(json);
obj.always();

This is how to serialize object with its functions:

   JSON.stringify(YOUR_OBJECT, function (key, value) {
        if (typeof value === 'function') {
            return value.toString();
        }
        return value;
    });

and this is how to deserialize it back:

JSON.parse(YOUR_JSON_STRING, function (key, value) {
     if (value 
         && typeof value === "string" 
         && value.substr(0,8) == "function") {
         var startBody = value.indexOf('{') + 1;
         var endBody = value.lastIndexOf('}');
         var startArgs = value.indexOf('(') + 1;
         var endArgs = value.indexOf(')');

         return new Function(value.substring(startArgs, endArgs)
                           , value.substring(startBody, endBody));
     }
     return value;
 });
发布评论

评论列表(0)

  1. 暂无评论