saw*_*awa 6 javascript arrays string json stringify
我试图JSONify Javascript对象只是为了得到"无效的字符串长度"错误.我决定将对象分成更小的部分,在较小的部分上使用JSON.stringify,并将每个段追加到文件中.
我首先将javascript对象转换为数组并将它们拆分为更小的部分.
{'key1': [x, y, z], 'key2' : [p, q, l], ...... } - JSON表示法中的原始对象样本.每个字符x, y, z, p, q, l都是base 64字符串的缩写,其长度足以导致字符串长度溢出问题.
[ ['key1', x], ['key1', y], ['key1', z], ['key2', p], ....... ] - 数组转换
var arrays = []
while (arrayConvertedObject.length > 0)
arrays.push(arrayConvertedObject.slice(0, 2))
}
Run Code Online (Sandbox Code Playgroud)
然后我打算为每个较小的数组创建一个javascript对象,分别arrays使用JSON.stringify.
[["key1", x], ["key1", y]] - array 1
[["key1", z], ["key2", p]] - array 2
Run Code Online (Sandbox Code Playgroud)
当我将每个较小的数组转换为Javascript对象并使用JSON.stringify时,我得到:
{"key1": [x, y]} - string 1
{"key1": [z], "key2": [p]} - string 2
Run Code Online (Sandbox Code Playgroud)
问题是带有额外操作的字符串连接},{将不会保留原始数据:
{"key1": [x, y], "key1": [z], "key2": [p]}
Run Code Online (Sandbox Code Playgroud)
当我想要obj["key1"]时[x, y, z],上面的JSON将被解析obj["key1"] = [z].
如果我不在较小的对象上使用JSON.stringify,它将击败我JSONifying一个大的javascript对象的原始目标.但是如果我这样做,我就无法连接具有重复键的JSONified小对象.
有没有更好的方法来处理JSON.stringify"无效的字符串长度"错误?如果没有,有没有办法连接JSONified对象而不重写重复键?
感谢您阅读冗长的问题.任何帮助将不胜感激.
下面的解决方案使用直接字符串操作。
没有做过任何性能比较。
var x="X", y="Y", z="Z", p="P";
// your starting arrays
var subArrs = [ ['key1', x], ['key1', y], ['key1', z], ['key2', p]];
// the result should be in this string
var jsonString = "{}";
// take each subArray
subArrs.map(function(subArr) {
var key = subArr[0];
var val = subArr[1];
// try to look for the key in the string
var keyMatcher = '"'+key+'":\\[';
var endOfObjectMatcher = '\\}$';
var regexStr = keyMatcher + '|' + endOfObjectMatcher;
jsonString = jsonString.replace(new RegExp(regexStr), function(match){
if (match=='}') {
// the end of the object has been matched,
// so simply append the new key-value pair
return ',"'+key+'":['+JSON.stringify(val)+"]}";
} else {
// an existing key has been found,
// so prepend the value to the beginning of the array
// (match contains something like: '"somekey":['
return match + JSON.stringify(val) + ",";
}
});
});
// replace the falsely added first comma in the object
jsonString = jsonString.replace('{,','{');
// print it here
document.write(">>" + jsonString + "<br/>");Run Code Online (Sandbox Code Playgroud)
body {
font-family: monospace;
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6351 次 |
| 最近记录: |