gpt4 book ai didi

Javascript对象序列化函数

转载 作者:行者123 更新时间:2023-11-28 19:30:14 25 4
gpt4 key购买 nike

我需要一个可以在没有 JSON.stringify 的情况下序列化 {"a":"val", "b":{}, "c":[{}]} 类型的对象的函数(因为环境根本没有JSON 对象)或使用 jquery 和任何其他库。下面的代码是我现在所拥有的:

function objToString(obj) {
if (obj == null) return null;
var index = 0;
var str = '{';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += index != 0 ? "," : "";
str += '"' + p + '":' + (typeof (obj[p]) == 'object' ? objToString(obj[p]) : itemToJsonItem(obj[p]));
index++;
}
}
str += "}";
return str;
}

function itemToJsonItem(item) {
return isNaN(item) ? '"' + item + '"' : item;
}

该函数可以处理对象、嵌套对象,但不能处理数组。上述对象中的节点“c”看起来像“c”:{“0”:{...}},而不像数组。不足为奇的 "c".constructor === Array 是 false,因为它解释为函数而不是数组。这是完整的代码,您可以在其中看到发生了什么。

<div id="div_result"></div>

<script>
var test = { "a": "val", "b": [{"c":"val c"}]};

function objToString(obj) {
if (obj == null) return null;
var index = 0;
var str = '{';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += index != 0 ? "," : "";
str += '"' + p + '":' + (typeof (obj[p]) == 'object' ? objToString(obj[p]) : itemToJsonItem(obj[p]));
index++;
}
}
str += "}";
return str;
}

function itemToJsonItem(item) {
return isNaN(item) ? '"' + item + '"' : item;
}

document.getElementById("div_result").innerHTML = objToString(test);
</script>

我真的很感激帮助,此时每个对象内部的 toSerialize 函数创建的序列化对象,但我们希望使用外部标准函数来创建它。

最佳答案

尝试使用JSON 3 。它是 window.JSON 的 polyfill 库。它公开了 JSON.stringifyJSON.parse 方法。

关于Javascript对象序列化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com