javascript - JSON.Stringify 替换函数无法获取键值

标签 javascript jquery json

我正在使用 JSON.stringify 及其替换参数。但是在替换参数中我无法获取键和值,而不是我将键值作为空字符串“”并将值作为完整的 JSON 对象。我在我的代码中犯了什么错误?请清除它。

var replacer=function(key,value){
        debugger; 
    }
    $(function () {
       JSON.stringify({"name":'xxxxx'},replacer)
    });

我需要获取作为“name”的键和作为“xxxxx”的值

最佳答案

MDN - JSON.stringify(): The replacer parameter :

[...]Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified.[...]

在您的第一次迭代中,您将整个对象 {"name":'xxxxx'} 作为 value, 但是因为您从替换函数返回了 undefined,所以整个对象将被替换为 undefined,因此下一次使用值/键对的迭代不会发生。

如果您返回 value,您将看到下一次迭代发生。

var replacer = function(key, value) {
  console.dir(arguments);
  return value;
}

JSON.stringify({
  "name1": 'xxxxx'
}, replacer);

关于javascript - JSON.Stringify 替换函数无法获取键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675980/

相关文章:

javascript - 整个条形图的 Google Charts 堆叠条形图/柱形图注释

javascript - 创建一个相对于某个div具有绝对位置的div

java - 循环遍历 json 文件,将键值附加到列表

javascript - 想要更改数组传递的特定 id 上动态创建的按钮的颜色

javascript 聊天框/信使脚本

javascript - Selenium 没有注册按钮按下

jquery - 如何将 jQuery 自动完成与 Node.js 结合使用

javascript - HTML 中的 div 不是一一显示的吗?

Android 改造解析 JSON 预期为 BEGIN_OBJECT 但为 BEGIN_ARRAY

java - 如何使用 jolt 替换某些属性的文本