在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ json 合并了 拆分問題

json 合并了 拆分問題

后臺返回數(shù)據(jù)時兩個json合到一起了
格式如:

 var str = '{"employees":[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]}{"employees":[{"firstName":"Thomas","lastName":"Carter"}]}'
 
 

怎么拆分它呢?

回答
編輯回答
舊螢火

case by case的寫法
如果后端返回的數(shù)據(jù)確定是兩個并且返回的兩個json都是只有一個employees屬性的話:
用string的lastIndexOf找到分割點

const i = str.lastIndexOf('{"employees":')
const result = [JSON.parse(str.substr(0, i)), JSON.parse(str.substr(i))]
console.log(result)
2018年9月6日 10:36
編輯回答
浪蕩不羈

確定都是 object 并且是無縫連接

const arr = str.split('}{');
arr.length > 1 && arr.forEach((item, i) => {
  if (i === 0) {
    item += '}';
    console.log(JSON.parse(item));
  } else if (i === arr.length - 1) {
    item = '{' + item;
    console.log(JSON.parse(item));
  } else {
    item = `{${item}}`;
    console.log(JSON.parse(item));
  }
});
2017年12月26日 03:59