将eval解析转换为json.parse

时间:2012-12-28 00:32:32

标签: javascript json

这属于名为ProcessMaker的BPM应用程序,但逻辑和语法应相对相同。我试着 从另一个序列化网格填充网格(基本上是表格),其中数据已传递到隐藏字段。

传递给隐藏字段的数据格式如下:

例如:

{"1":{"id":"4332","product":"ball","price":"$5.00",”ordered":"On"}

在processmaker的wiki上找到的下面的javascript示例将隐藏字段作为对象反序列化,并使用其信息填充一个名为它的新网格。 processmaker的wiki上的示例使用eval函数,但是如何使用json.parse()函数转换它?

        function populateGrid() {
           var grd = getObject("newAccountsGrid");
           //remove all existing rows in the grid (except the first one): 
           var i = Number_Rows_Grid("newAccountsGrid", "accId");
           for (; i > 1; i--)
              grd.deleteGridRow(i, true);
           //The first row can't be deleted, so clear the fields in the first row:
           for (i = 0; i < grd.aFields.length; i++)
              getGridField("contactsGrid", 1, grd.aFields[i].sFieldName).value = "";
           //unserialize the hidden field as an object:
           var oAccounts = eval('(' + getField("sAccounts").value + ')'); 
           if (typeof oAccounts == 'object') { 
              for (var rowNo in oAccounts) {
                 if (rowNo != 1)
                    grd.addGridRow();
                 getGridField('newAccountsGrid', rowNo, 'accId').href = oAccounts[rowNo]["accountId"];
                 getGridField('newAccountsGrid', rowNo, 'accName').href = oAccounts[rowNo]["accountName"];
                 getGridField('newAccountsGrid', rowNo, 'createDate').href = oAccounts[rowNo]["created"];
              }
           }
        }
        populateGrid(); //execute when the DynaForm loads

3 个答案:

答案 0 :(得分:1)

这很简单:

var oAccounts = JSON.parse(getField("sAccounts").value);

答案 1 :(得分:0)

eval("("+something+")")JSON.parse(something)

答案 2 :(得分:0)

这个示例(ProcessMaker wiki)上面几行,是一个建议使用JSON.parse()的注释。 使用您的示例,您的代码应如下所示:

    function populateGrid() {
   var grd = getObject("newAccountsGrid");
   //remove all existing rows in the grid (except the first one): 
   var i = Number_Rows_Grid("newAccountsGrid", "accId");
   for (; i > 1; i--)
      grd.deleteGridRow(i, true);
   //The first row can't be deleted, so clear the fields in the first row:
   for (i = 0; i < grd.aFields.length; i++)
      getGridField("contactsGrid", 1, grd.aFields[i].sFieldName).value = "";
   //unserialize the hidden field as an object:
   var oAccounts = JSON.parse(getField("sAccounts").value); 
   if (typeof oAccounts == 'object') { 
      for (var rowNo in oAccounts) {
         if (rowNo != 1)
            grd.addGridRow();
         getGridField('newAccountsGrid', rowNo, 'accId').href = oAccounts[rowNo]["accountId"];
         getGridField('newAccountsGrid', rowNo, 'accName').href = oAccounts[rowNo]["accountName"];
         getGridField('newAccountsGrid', rowNo, 'createDate').href = oAccounts[rowNo]["created"];
      }
   }
}
populateGrid(); //execute when the DynaForm loads