我有一個包含大量資料的 JSON,這是一個例子:
{
"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"
}
]
}
}
我想提取textkey的值,不管key在哪里。我正在嘗試使用鍵檢查鍵,Object.keys但它只回傳頂級鍵:
for (let x of Object.keys(someJson)) {
console.log(x);
}
我怎樣才能找到這個 JSON 中的所有值text,不管它在 JSON 中的哪個位置?
uj5u.com熱心網友回復:
您可以使用JSON.stringify技巧,您可以從中攔截所有密鑰
function find(obj: object, key: string) {
const ret: any[] = [];
JSON.stringify(obj, (_, nested) => {
if (nested && nested[key]) {
ret.push(nested[key]);
}
return nested;
});
return ret;
};
...
const o = {
key: '123',
a: {
key: 'hello',
b: [
{
c: {
key: 123,
},
},
],
},
};
it('123', () => {
console.log(JSON.stringify(find(o, 'key'))); // ["123","hello",123]
});
uj5u.com熱心網友回復:
如果您想要通用 JSON,只需呼叫此函式并傳遞您的物件:
function printText(obj){
if(Array.isArray(obj)){
for(const o of obj){
printText(o);
}
}else if(typeof obj === "object"){
if (obj){
for(const o of Object.keys(obj)){
if(o==="text"){
console.log(obj.text);
}else{
printText(obj[o]);
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338281.html
上一篇:如何在現有JSON中添加新行
