2016-05-09 23 views
23

içinde bir json nesnesi olup olmadığını nasıl kontrol ederim Bir JSON veya bir URL'den metin almak için fetch polyfill kullanıyorum, yanıtın bir JSON nesnesi olup olmadığını nasıl kontrol edebilirim? Bir getirme yanıtının javascript

fetch(myRequest).then(response => { 
    const contentType = response.headers.get("content-type"); 
    if (contentType && contentType.indexOf("application/json") !== -1) { 
    return response.json().then(data => { 
     // process your JSON data further 
    }); 
    } else { 
    return response.text().then(text => { 
     // this is text, do something with it 
    }); 
    } 
}); 

içeriğin geçerli JSON olduğundan kesinlikle emin olmak gerekiyorsa

(ve don': sadece metin

fetch(URL, options).then(response => { 
    // how to check if response has a body of type json? 
    if (response.isJson()) return response.json(); 
}); 
+0

http: // stackoverflow com/a/20392392/402037 – Andreas

cevap

44

this MDN example gösterildiği gibi, tepkinin content-type için kontrol edebilir olduğunu Başlıklara güvenme), her zaman yanıtı sadeceolarak kabul edebilirsiniz.ve kendiniz ayrıştırmak:

fetch(myRequest) 
    .then(response => response.text()) 
    .then(text => { 
    try { 
     const data = JSON.parse(text); 
     // Do your JSON handling here 
    } catch(err) { 
     // It is text, do you text handling here 
    } 
    }); 

Async/

bekliyor Eğer async/await kullanıyorsanız, daha doğrusal bir biçimde yazabilirim:

async function myFetch(myRequest) { 
    try { 
    const reponse = await fetch(myRequest); // Fetch the resource 
    const text = await response.text(); // Parse it as text 
    const data = JSON.parse(text); // Try to parse it as json 
    // Do your JSON handling here 
    } catch(err) { 
    // This probably means your response is text, do you text handling here 
    } 
} 
İlgili konular