2016-07-22 62 views
0

我必須解析一個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; 

我的問題是,有沒有更好的方式來以更有效的方式做到這一點?

+3

可能會更好過://codereview.stackexchange。 com/ – tymeJV

+1

不要嘗試所有的東西,只是可能爆炸的部分... – dandavis

回答

1

如何:

switch (typeof authors) { 
    case 'object': 
     if (Array.isArray(authors)) { 
      authors = authors.map((author) => { 
       if (typeof author === 'object' && author.name) { 
        return author.name; 
       } else { 
        return author; 
       } 
      }); 
     } else { 
      authors = [authors.name]; 
     } 
    break; 
    case 'string': 
     authors = authors.split(','); 
    break; 
    case 'undefined': 
     // 
    break; 
} 
1

只是爲了記錄:這裏是一個最低限度的,但功能的版本。

switch((Array.isArray(authors) && 1) | (typeof authors[0] == 'string' && 2)) { 
    case 0: return [authors.name]; 
    case 1: return [authors[0].name]; 
    case 2: return authors.split(','); 
    case 3: return authors; 
} 

JSFiddle

不用說,與在發生意外輸入,以及一個最低限度的保護...

在http
相關問題