【问题标题】:Deserialize possible children, which might have properties that needs to be deserialized反序列化可能的子节点,这些子节点可能具有需要反序列化的属性
【发布时间】:2018-02-22 17:27:41
【问题描述】:

在我的 ASP.NET 后端,我使用 SignalR 返回一个名为 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 方法。

【问题讨论】:

  • 我添加了答案。我希望它会按照您的期望工作。谢谢

标签: javascript json ecmascript-6 signalr


【解决方案1】:

1.如果作业有 json 属性,只需执行 job.json = JSON.parse(job.json)

2.如果作业有孩子,遍历所有孩子

3.重复1

假设,在一项工作中,您同时拥有带有JSON stringchildren 的json 属性,那么我们必须一个接一个地执行这两个点(1 和2),以将作业的嵌套json 属性转换为JSON Object

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

尝试使用ES6 Arrow 函数的数组filter() 方法。

工作演示:

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

【讨论】:

  • 效果很好!添加了一些额外的孩子,它们有多个孩子,那些也有孩子(这里有点像边缘套),而且效果也很好!谢谢:)
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 2022-06-27
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多