将列表转换为Json数组

时间:2016-01-20 10:58:31

标签: javascript

我从后端获取以下格式的数据:

[{
    patientId=2501, 
    uniqueId=PID140, 
    firstName=bairava, 
    middleName=, 
    lastName=surya, 
    emailAddress=**1717259005##@noemailaddress.com, 
    birthday=2016-01-07 00:00:00.0, 
    portraitId=0, 
    race=, 
    companyId=10253, 
    ssn=123-54-7678, 
    ethnicity=0, 
    bloodGroup=0, 
    gender=1, 
    patientLanguageId=,         
    folderId=53501, 
    activationReason=, 
    deactivationReason=, 
    patientStatus=Active, 
    activationRequest=false, 
    cashPayment=true
}]

我如何单独迭代并获取每个细节?

1 个答案:

答案 0 :(得分:0)

很难解释。只需阅读代码并尝试理解。

方法是将此string转换为JavaScript结构对象。

// The output html from the server
var msglis='[{ patientId=2501, uniqueId=PID140, firstName=bairava, middleName=, lastName=surya, emailAddress=**1717259005##@noemailaddress.com, birthday=2016-01-07 00:00:00.0, portraitId=0, race=, companyId=10253, ssn=123-54-7678, ethnicity=0, bloodGroup=0, gender=1, patientLanguageId=, folderId=53501, activationReason=, deactivationReason=, patientStatus=Active, activationRequest=false, cashPayment=true }, { patientId=2506, uniqueId=PID140, firstName=bairava, middleName=, lastName=surya, emailAddress=**1717259005##@noemailaddress.com, birthday=2016-01-07 00:00:00.0, portraitId=0, race=, companyId=10253, ssn=123-54-7678, ethnicity=0, bloodGroup=0, gender=1, patientLanguageId=, folderId=53501, activationReason=, deactivationReason=, patientStatus=Active, activationRequest=false, cashPayment=true }]';

var arr = msglis.replace(/=/g, ':').replace(/:.*?[,}]/g, function(a, b, c) {
  console.log(c);
  var comma = a.indexOf(',') > -1;
  var val = a.replace(':', '').replace(',', '');
  
  if (/^\d+$/g.test(val)) {
    return a;
  }
  else {
    return ':"' + val + '"' + (comma ? ',' : '}');
  }
});


var obj = eval(arr);
document.body.innerHTML = JSON.stringify(obj);

您可以看到regex在行动here