如何将字符串转换为angular typescript中的对象数组

时间:2018-03-01 06:10:05

标签: json angular typescript

我有以下字符串,如何将其转换为对象数组

{"Car":
"["
   {"Carid":234,"CompanyCode":null}","
   {"Carid":134,"CompanyCode":"maruti"}","
   {"Carid":145,"CompanyCode":"sedan"}","

"]"
}

尝试了JSON.parse,它给出了错误意外的令牌' {'在11位

尝试了eval,它给出了错误意外的令牌':'

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式来解决此类问题



let s = '{"Car":"[" {"Carid":234,"CompanyCode":null}"," {"Carid":134,"CompanyCode":"maruti"}","{"Carid":145,"CompanyCode":"sedan"}",""]"}';


let matchReplace = [['"\\,"',','],['"\\["','['],['\\,"\\]"',']']];
matchReplace.forEach((reg)=>{
  let regularExp = new RegExp(reg[0],'g');
  s = s.replace(regularExp,reg[1])
});

console.log(JSON.parse(s));