【问题标题】:Iterative function to intercept values by key通过键截取值的迭代函数
【发布时间】: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;
});

【问题讨论】:

标签: json typescript


【解决方案1】:

如果您的目标只是获取关键文本,您可以使用以下方法。

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));

【讨论】:

    【解决方案2】:

    我不确定我是否明白了这个问题,但这里是 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?'
    // ]
    

    【讨论】:

    • 你误解了我的意思。我想为键 text 旁边的每个值获取一个值数组。
    • @GilbertWilliams Chenged 回答递归获取text 值数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2017-12-03
    相关资源
    最近更新 更多