我必須解析一個json對象,該對象可以是字符串,數組,字符串數組和對象數組。我意識到一開始一個對象可能有多種類型,但我不能從上游更改代碼,所以我不得不在我的代碼中處理它。我正在爲現代瀏覽器構建一個像素庫,所以我沒有使用jQuery或lodash。我支持大多數流行的瀏覽器和IE> = 9JavaScript來容納字符串,對象和數組
這裏是一個可以返回
"author": {
"@type": "Person",
"name": "Author"
}
或者
"author":[{"@type":"Person","name":"Author"}]
或者
"author": 'Author'
或數據的例子
"author": ['Author', 'Author1']
這是我的代碼。
let obj = {};
try {
const json = document.querySelector('div.json');
if (json) {
let disc = JSON.parse(json.innerHTML);
let authors = disc.author;
if (typeof authors !== 'undefined' && Array.isArray(authors) && authors.length > 0) {
authors = authors.map((author) => {
if (typeof author === 'object' && author.name) {
return author.name;
} else {
return author;
}
});
}
if (typeof authors !== 'undefined' && !Array.isArray(authors) && typeof authors === 'object') {
authors = [authors.name];
}
if (typeof authors !== 'undefined' && typeof authors === 'string') {
authors = authors.split(',');
}
obj.cAu: authors.join(',');
}
} catch (e) { }
return obj;
我的問題是,有沒有更好的方式來以更有效的方式做到這一點?
可能會更好過://codereview.stackexchange。 com/ – tymeJV
不要嘗試所有的東西,只是可能爆炸的部分... – dandavis