【问题标题】:Parse JSON array inside array and bind with pdfmake解析数组内的 JSON 数组并与 pdfmake 绑定
【发布时间】:2020-04-16 00:04:41
【问题描述】:

我是 Angular 的新手,我正在尝试解析我的数组中的一个数组,我无法解析这个数组,因为使用我的代码它出现了错误 Unexpected token u in JSON at position 0,我'已经在互联网上搜索了很多示例,但在我的情况下没有工作,我不明白我的代码有什么问题,非常感谢您的帮助。

数据

{ 
"employees":[ 
  { 
     "id":"f790cb86-4d41-401c-2a45-08d745b83164",
     "firstName_FL":"Employee Name",
     "employeeJobStatuses":[ 
        { 
           "id":"bd58a1a3-6dd7-4cd5-6c79-08d76cf25ba3",
           "status":"STATUS_ACTIVE"
        }
      ]
    }
  ]
}

employees.component.ts

   table: {
        headerRows: 1,
        widths: [ '*', '*', '*', '*', '*', '*' ],
        alignment: 'center',
        body: [[
        {text: 'Name', style: 'header'}, 
        {text: 'Position', style: 'header'},
        {text: 'Department', style: 'header'},
        {text: 'Hiring Date', style: 'header'}, 
        {text: 'First Contracting Salary', style: 'header'},
        {text: 'Status', style: 'header'},
      ]]
            .concat(this.jsonObj.map((element, i) => 
            [
             element['firstName_FL'],
             element['position']['name_FL'],
             element['department']['name_FL'],
             element['hiringDate'].slice(0, 10),
             element['firstContractingSalary'],
             element.employeeJobStatuses.map((x, j) => ({ ...x,
              Status: x
            }))
            ]
            ))

      }

除了这一行 JSON.parse(element['employeeJobStatuses']['status'])

【问题讨论】:

  • element['employeeJobStatuses']['status']) 这应该类似于 element['employeeJobStatuses'][i].status])
  • @EugeneSunic 我试过了,但出现错误无法读取未定义的属性“状态”
  • 您的 json 格式不正确(输入 json),您缺少数组结尾和逗号
  • 是的,我已经编辑并更正了我的问题
  • 但他们仍然坚持......

标签: javascript json angular typescript


【解决方案1】:

将你的输入解析为一个有效的 JS 对象,然后用它做任何需要做的事情。

// your input
const jsonString = JSON.stringify({
  "data": {
    "employee": [{
      "id": "f790cb86-4d41-401c-2a45-08d745b83164",
      "firstName_FL": "Employee Name",
      "employeeJobStatuses": [{
        "id": "bd58a1a3-6dd7-4cd5-6c79-08d76cf25ba3",
        "status": "STATUS_ACTIVE"
      }]
    }]
  }
})
// parse your input to js valid object
const jsonObj = JSON.parse(jsonString);

// do wathever you need to do
const newObj = jsonObj.data.employee.map((element, i) => ({
  ...element,
  employeeJobStatuses: element.employeeJobStatuses.map((x, j) => ({ ...x,
    status: x.status
  }))
}))

console.log(newObj);

【讨论】:

  • 我尝试过这种方法,但遇到了同样的错误
  • 你能不能从这个例子开始,因为你不能从中得到错误。如果你已经有一个有效的 js 对象(数据),我什至不确定为什么你需要解析两次`JSON.parse(element['employeeJobStatuses']['status'])`
  • 好的,既然我不需要通过两次,为什么会出现这个错误
  • 我相信因为我们说的第一件事element['employeeJobStatuses']['status'],你需要像我一样做,映射你的元素['employeeJobStatuses'] 因为它是一个数组,你不能只拉它的状态
  • 当我把它放在一个数组中时它现在工作得很好 element.employeeJobStatuses.map((x, j) => [] 非常感谢你的帮助,如果没有我永远不会这样做你
猜你喜欢
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多