我有一个像这样的对象字符串:

my_object_string = `{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
    "key5": "value5",
    "key6": "value6",
    "key7": "value7",
    "key8": "value8"
}`;

如果我想解析整个对象,我将使用:
my_object = JSON.parse(my_object_string); // Stores object with all key-value pairs from key1 to key8

我需要做的是仅存储特定键,而在解析时忽略其他键。

我尝试了reviver函数来仅获取key2,key5和key8,但无法正常工作:
my_object = JSON.parse(my_object_string, (key, value) =>
  /(?:key2)|(?:key5)|(?:key8)/.test(key)
    ? value
    : null
);

我尝试获取的结果对象应类似于:
my_object = {
    "key2": "value2",
    "key5": "value5",
    "key8": "value8"
};

我只想使用基本的JavaScript代码(不使用框架库)。也只能在JSON.parse(text, reviver)的reviver函数中播放以获得特定的键。

最佳答案

传递给reviver函数的最后一个键为空,因为它对应于整个对象,因此在您的情况下,应返回它而无需更改。您也可以使用数组indexOf方法代替regexp。

var my_object = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key4": "value4",
  "key5": "value5",
  "key6": "value6",
  "key7": "value7",
  "key8": "value8"
};
var my_object_string = JSON.stringify(my_object);

var keys = ['key2', 'key5', 'key8'];
var my_object2 = JSON.parse(my_object_string, function(k,v){
  if (k) {
    return keys.indexOf(k) !== -1 ? v : undefined;
  }
  else {
    // no key means root object
    return v;
  }
});
console.log(my_object2);

07-24 19:33