【发布时间】:2021-12-15 11:51:57
【问题描述】:
我有一个大的 JSON 文件,我想截取所有与它们关联的键 text 的值,例如:
type":"doc",
"content":[
{
"type":"paragraph",
"content":[
{
"text":"this is a simple page, about a simple umbrella.",
"type":"text"
}
]
},
{
"type":"paragraph",
"content":[
{
"text":"you can use this text to find the umbrella page.",
"type":"text"
}
]
},
{
"type":"paragraph",
"content":[
{
"text":"do you like it?",
"type":"text"
}
]
},
我知道我可以使用Object.keys,但这仅涵盖“顶级”,并没有深入。
我不想为此使用递归,而是使用迭代函数。
我尝试使用JSON.stringify,但性能不佳:
const obj = JSON.parse(content);
let ret = '';
JSON.stringify(obj, (_, nested) => {
if (nested && nested[key]) {
ret += nested[key] + '\n';
}
return nested;
});
【问题讨论】:
-
您可以使用 reviver 参数 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 修改
JSON.parse中的字段值
标签: json typescript