node.js JSON.parse reviver 不报告重复键?

node.js JSON.parse reviver doesn't report duplicate keys?

我正在尝试使用 JSON 解析器来检测并保存重复键。我在 node.js 中将 JSON.parse() 与 reviver 一起使用,我希望它会在我获得重复密钥时告诉我。然而事实并非如此。还有别的办法吗?有没有更好的 JSON 解析器来处理 reviver 或其他参数中的重复键?

"use strict";

try {
    var content = '{"value": "a", "value": "b", "value": "c" }';
    console.log(content);
    var parsed = JSON.parse(content, function(k, v) {
        console.log(k+"="+JSON.stringify(v));
        return v;
    });
} catch (e) {
    console.log(e);
}

输出为:

{"value": "a", "value": "b", "value": "c" }
value="c"
={"value":"c"}

JSON.parse() parses the string the same way whether or not you provide a reviver function(换句话说,当传入 reviver 时,它不会切换到 "streaming parser")。提供一个 reviver 函数只是为了方便,这样就不必自己编写必要的循环了。

npm 上有 一些流式 JSON 解析器,例如:clarinet, JSONStream, and oboe。这是对这 3 个的小测试:

var clarinet = require('clarinet').parser();
var JSONStream = require('JSONStream').parse('*', function (value, path) {
  return { key: path[path.length - 1], value: value, path: path }
});
var rs = new (require('stream').Readable)();
rs._read = function(n) {};
var oboe = require('oboe')(rs);

var content = '{"value": "a", "value": "b", "value": "c" }';

clarinet.onopenobject = clarinet.onkey = function(k) {
  console.log('clarinet key =', k);
};
clarinet.onvalue = function(v) {
  console.log('clarinet value =', v);
};
clarinet.write(content).close();

JSONStream.on('data', function(d) {
  console.log('JSONStream data:', arguments);
}).end(content);

oboe.on('node:*', function(n) {
  console.log('oboe node:', arguments);
});
rs.push(content);
rs.push(null);

// output:
// clarinet key = value
// clarinet value = a
// clarinet key = value
// clarinet value = b
// clarinet key = value
// clarinet value = c
// JSONStream data: { '0': { key: 'value', value: 'a', path: [ 'value' ] } }
// JSONStream data: { '0': { key: 'value', value: 'b', path: [ 'value' ] } }
// JSONStream data: { '0': { key: 'value', value: 'c', path: [ 'value' ] } }
// oboe node: { '0': 'a', '1': [ 'value' ], '2': [ { value: 'a' }, 'a' ] }
// oboe node: { '0': 'b', '1': [ 'value' ], '2': [ { value: 'b' }, 'b' ] }
// oboe node: { '0': 'c', '1': [ 'value' ], '2': [ { value: 'c' }, 'c' ] }
// oboe node: { '0': { value: 'c' }, '1': [], '2': [ { value: 'c' } ] }