【问题标题】:How to access JSON object from xml2js in Angular?如何在 Angular 中从 xml2js 访问 JSON 对象?
【发布时间】:2021-03-01 16:35:52
【问题描述】:

我正在使用 xml2js 在 Angular 中将一些 xml 转换为 json,如下所示:

showData() {
    xml2js.parseString(this.xml, (err, result) => {
      this.text = result;
      console.log(this.text);
    })
  }

效果很好,我在控制台中获取了 JSON,但我无法弄清楚如何访问特定数据。 JSON 格式如下所示:

我想访问idmaxlengthnametype 内的属性UIElement。我想 console.log 并使用这些属性中的值,但不知道该怎么做。

【问题讨论】:

  • console.log(this.text['cm:property-placeholder']['cm:default-properties][0]['UIElement'][0]['$']) 获取对象。然后从那里添加idmaxlength 等到最后以获取各个元素
  • @rhavelka 我最初尝试过,但收到错误Cannot read property '0' of undefined
  • 你知道它是在cm:default-properties 还是UIElement 上,你得到了错误。当我们弄清楚事情时,我会更新我的答案
  • 我在评论和回答中错过了UIInput 层。我会更新的

标签: json angular typescript


【解决方案1】:

我首先要做的是将您的 UIElement 数组放入它自己的数组中。所以你会做这样的事情

const uiElmentArray = this.text['cm:property-placeholder']['cm:default-properties'][0]['UIInput'][0]['UIElement'];

/**
uiElementArray = [
    {$: {id: 'customerName', ...}},
    {$: {id: 'mm_test_aggregate.interval', ...}},
    ...
]
**/

您可以从那里映射内容以从数组中删除 $

const updatedArray = uiElementArray.map(uiElement => uiElement.$);

/**
updatedArray = [
    {id: 'customerName', ...},
    {id: 'mm_test_aggregate.interval', ...},
    ...
];
**/

从那里你可以循环显示你的元素

updatedArray.forEach(uiElement => {
   console.log(uiElment)
});

使最终代码看起来像这样:

showData() {
    xml2js.parseString(this.xml, (err, result) => {
      const uiElementArray = result['cm:property-placeholder']['cm:default-properties'][0]['UIInput'][0]['UIElement'];
      const updatedArray = uiElementArray.map(uiElement => uiElement.$);
      updatedArray.forEach(uiElement => {
          console.log(uiElment)
      });
    })
  }

可以浓缩成这样的东西

showData() {
    xml2js.parseString(this.xml, (err, result) => {
      this.myData = result['cm:property-placeholder']['cm:default-properties'][0]['UIInput'][0]['UIElement'].map(uiElement => uiElement.$);
    })
  }

【讨论】:

  • 现在收到错误Cannot read property 'cm:property-placeholder' of undefined
  • 那是我的错字。我有this.text['cm:property-placeholder'],它应该是result['cm:property-placeholder']。我更新了我的代码
  • 是的,我也发现了。它工作得很好。谢谢!
猜你喜欢
  • 2017-08-16
  • 1970-01-01
  • 2021-04-07
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 2015-04-20
  • 2022-07-06
相关资源
最近更新 更多