Bird
0
0

This code snippet tries to parse JSON from an API response but throws an error:

medium📝 Debug Q7 of 15
Rest API - REST API Fundamentals
This code snippet tries to parse JSON from an API response but throws an error:
fetch('https://api.example.com/data')
.then(response => response.text())
.then(data => JSON.parse(data))
.then(parsed => console.log(parsed))
.catch(err => console.error(err))

What is the best fix?
AAdd await before fetch
BRemove JSON.parse call
CChange response.text() to response.json()
DUse response.blob() instead of response.text()
Step-by-Step Solution
Solution:
  1. Step 1: Understand response methods

    response.text() returns raw text; response.json() parses JSON automatically.
  2. Step 2: Identify the fix to avoid manual JSON.parse error

    Using response.json() removes need for JSON.parse and prevents errors.
  3. Final Answer:

    Change response.text() to response.json() -> Option C
  4. Quick Check:

    Use response.json() to parse JSON safely [OK]
Quick Trick: Use response.json() to parse JSON automatically [OK]
Common Mistakes:
MISTAKES
  • Parsing JSON twice causing errors
  • Using response.text() then JSON.parse manually
  • Confusing response.blob() with JSON parsing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes