javascript - JSON.parse Reviver函数: Access to object being revived?

标签 javascript json

我想确认我所看到的有关 this 引用的行为,以及使用 reviver 函数修改对象中的键(而不仅仅是值)的能力。

如果我使用 function(key,value {...} 传递我的 reviver 函数,而不是使用箭头函数 (key, value) => {...},此引用似乎指的是正在恢复的对象。这对于 JSON 中的子对象也是如此。我在服务器上的 Node.js 8.x 以及当前的 Chrome 中看到了这一点客户端。

可以理解的是,如果我将函数作为箭头函数传递,则调用上下文将被保留。

我在解析 JSON 时依靠它来添加和删除一些键。

我可以依赖这种行为吗?

var aTestStr = '{"prop1": "this is prop 1",'
    +'"prop2": {"prop2A": 25, "prop2B": 13, "prop2C": "This is 2-c"}'
                +'}';
var aTestObj = JSON.parse(aTestStr, function(key, value) {
    //at this point, this refers to the object being revived
    //E.g., when key == 'prop1', this is an object with prop1 and prop2
    //when key == prop2B, this is an object with prop2A, prop2B and prop2C
    //So is this code reliable?
    if (key == this.prop2B) {
        //Do something, add a prop to this:
        this.prop2BDif = 100 - this.prop2B;
    }
});

最佳答案

是的,已记录:JSON.parse documentation in the MDN

If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. Then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments.

关于javascript - JSON.parse Reviver函数: Access to object being revived?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688816/

相关文章:

JavaScript,DOM : appendChild and textContent

javascript - 有没有比 insertAdjacentHTML() 和一个巨大的 HTML 字符串更好的方法将 HTML 插入到 DOM 中?

json - golang : Unmarshal: json: cannot unmarshal array into Go value of type main. MonitorServerInfo

json - R:将具有空元素的嵌套列表转换为 data.frame(来自 json)

javascript - node.js TypeError : path must be absolute or specify root to res. sendFile [无法解析JSON]

JavaScript 数组未对齐

javascript - Electron 标题栏 “no-drag”和 “drag”无法正常工作

javascript - 在 Three.js 中使用 sprite 或 BufferedGeometry 是否性能更高?

php - JSON 不使用 PHP 解析

java - 从 JSONArray 获取字符串到 String[] 或 List<String> 以输入到 ArrayList