我有一個很大的 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;
});
uj5u.com熱心網友回復:
如果您的目標只是獲取關鍵文本,則可以使用以下方法。
var reg = /(?<=\")\w (?=\"\:)/g
var jsonValue = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}';
console.log(jsonValue.match(reg));
uj5u.com熱心網友回復:
不確定我是否抓住了這個問題,但這是lodash解決方案:
const _ = require('lodash');
const data = '{"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"}]}]}';
const obj = JSON.parse(data);
const getText = (obj) => {
const result = Object.entries(obj).reduce((acc, [key, value]) => {
if (key === 'text') acc.push(value);
if (_.isObject(value)) acc.push(...getText(value));
if (_.isArray(value)) value.map((item) => getText(item));
return acc;
}, []);
return result;
}
console.log(getText(obj));
// [
// 'this is a simple page, about a simple umbrella.',
// 'you can use this text to find the umbrella page.',
// 'do you like it?'
// ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343653.html
