代码之家  ›  专栏  ›  技术社区  ›  MortenMoulder

反序列化可能的子级,这些子级可能具有需要反序列化的属性

  •  0
  • MortenMoulder  · 技术社区  · 7 年前

    在我的ASP上。NET后端,我返回一个模型数组,称为 Job ,可以有 n 使用信号器的子级作业量。一份工作可能是这样的:

    {
      "id": 0,
      "json": '{"error": "Some error"}',
      "children": [{
        "id": 1
      }, {
        "id": 3,
        "children": [{
          "id": 4,
          "json": '{"error": "Some other error"}'
        }]
      }]
    }
    

    正如你所看到的,每个工作都可以有一个孩子,而这个孩子可以有另一个孩子,等等。每个作业还具有 json 属性,它是文本字符串中的JSON。我想将这些反序列化为常规JavaScript对象,如下所示:

    var deserialized = {
      "id": 0,
      "json": {
          "error": "Some error"
      },
      "children": [{
        "id": 1
      }, {
        "id": 3,
        "children": [{
          "id": 4,
          "json": {
              "error": "Some other error"
          }
        }]
      }]
    }
    

    基本上是这样的:

    1. 如果作业有 json 属性只需执行 job.json = JSON.parse(job.json)
    2. 如果工作有子项,则遍历所有子项
    3. 重复1次

    我怎样才能做到这一点?我想递归是一种方法,但我宁愿看看是否有可能利用新的ES6方法。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Rohìt Jíndal    7 年前

    如果作业具有json属性,只需执行作业即可。json=json。解析(job.json)

    2、如果工作有子项,则循环遍历所有子项

    3、重复1

    假设,在作业中,两个属性都是json JSON string 还有 children 然后,我们必须逐个执行两个点(1和2),以转换嵌套 json 作业的属性 JSON Object .

    在这种情况下,首先我们必须转换 json 属性转换为 JSON对象 然后,我们必须再次使用子数组迭代整个作业。

    尝试阵列 filter() 方法 ES6 Arrow 作用

    工作演示:

    let jobs = [{
      "id": 0,
      "json": '{"error": "Some error"}',
      "children": [{
        "id": 1
      }, {
        "id": 3,
        "children": [{
          "id": 4,
          "json": '{"error": "Some other error"}'
        }]
      }]
    },
    {
      "id": 1,
      "json": '{"error": "Some error"}',
      "children": [{
        "id": 2
      }, {
        "id": 4,
        "children": [{
          "id": 5,
          "json": '{"error": "Some other error"}'
        }]
      }]
    }];
    
    function parseObj(job) {
     let res;
     if (typeof job !== 'object') {
      	return;
     } else {
     	res = job.filter(elem => (elem.json && typeof elem.json == 'string')?elem.json = JSON.parse(elem.json):parseObj(elem.children))
        .filter(elem => (elem.json && typeof elem.json == 'string')?elem.json = JSON.parse(elem.json):parseObj(elem.children));
     }
     return res;
    }
    
    
    console.log(parseObj(jobs));