我需要使用JSON将此字符串序列化为多维数组。你会怎么做?
{FRMB [0] [的CssClass] = textarea的&安培; [0] [必需] FRMB =真安培; [0] [值] =对&安培FRMB; FRMB [1] [的CssClass] =广播安培; FRMB [1] [需要] =真安培; FRMB [1] [标题] = RDO&安培; FRMB [1] [值] [2] [值] =一个&安培; FRMB [1] [值] [2] [基线] =真安培; FRMB [1] [值] [3] [值] = 2&安培; FRMB [1] [值] [3] [基线] =假安培; FRMB [2] [的CssClass] = INPUT_TEXT&安培; FRMB [2] [必需] =假安培; FRMB [ 2] [值] =文本&安培; FRMB [3] [的CssClass] =复选框&安培; FRMB [3] [需要] =真安培; FRMB [3] [标题] = CHK&安培; FRMB [3] [值] [2] [值] = CHK + 1和; FRMB [3] [值] [2] [基线] =真安培; FRMB [3] [值] [3] [值] = CHK + 2及FRMB [3] [值] [3] [基线] =假安培; FRMB [4] [的CssClass] =选择&安培; FRMB [4] [需要] =假安培; FRMB [4] [多] =真&安培; FRMB [4] [标题] = SEL&安培; FRMB [4] [值] [2] [值] = SEL1&安培; FRMB [4] [值] [2] [基线] =真安培; FRMB [4] [值] [3] [值] = SEL2&安培; FRMB [4] [值] [3] [基线] =假安培; form_id =未定义}
修改 多维度真的让我无法将这个字符串转换为JSON。我试图剥离括号以获得数组的索引列表,但是以有用的方式重建数组一直是最大的挑战。
所以我一直在做:
private static List<string> StripBrackets(string input)
{
var ret = new List<string>();
var indx = 0;
do
{
input = input.TrimStart('[');
indx = input.IndexOf(']');
if(indx !=-1)
{
var newVal = input.Substring(0, indx);
ret.Add(newVal);
input = input.Remove(0, indx+1);
}
} while (indx != -1);
//-- this is where I bonked
string[,] results = new string[ret.Count, 23];
foreach (var r in ret)
{
}
return ret;
}
我一直在研究这个问题 - 因此疲惫/有限的问题。它开始觉得我这样做是“艰难的”,并想看看是否有人开悟有更好的想法。 TIA
答案 0 :(得分:2)
扩展@ ratchetfreak的评论:
var str = "{frmb...";
//sanitize string
str = str.substring(1, str.length-1); //remove braces
str = str.replace(/\[([a-z]+)\]/gi, '["$1"]'); //enclose non-numeric keys in double quotes
str = str.replace(/=([^&]+)/g, '="$1"'); //enclose values in double quotes
str = str.replace(/"(true|false)"/g, "$1"); //remove double quotes around boolean values
str = str.replace(/&/g, ";"); //replace all ampersands with semi-colons
//initialize "frmb"
var frmb = [];
for (var i = 0; i < 5 /* a guess as to how long "frmb" will be */; i++){
var values = [];
for (var j = 0; j < 5 /* a guess as to how long each "values" field will be */; j++){
values.push({});
}
frmb.push({values:values});
}
//evaluate as Javascript
eval(str);
//marshal to string
var result = JSON.stringify(frmb);
使这个解决方案难以实现通用的部分是你需要初始化“frmb”。例如,如果没有先将frmb[0].cssClass
初始化为数组,然后使用frmb
将对象添加到该数组,则无法调用push()
。因此,您需要估计您认为frmb
的大小,以及每个values
子阵列的大小。