MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Handling JSON Responses0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
8.1Fetching Data from APIs8.2Handling JSON Responses8.3GET vs POST Requests8.4Mini Project: Random Joke Generator
HomeTutorialsJavaScript for IntermediateHandling JSON Responses
GET vs POST Requests

Handling JSON Responses

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

JavaScript Object Notation (JSON) is the universal data interchange format of modern web services. When receiving responses via the Fetch API, reading and parsing JSON safely requires understanding response body streams and error handling.


1. The response.json() Method

The HTTP response body returned by fetch() is a readable stream. To parse this stream into a native JavaScript object, invoke response.json():

1async function loadUserData() {
2 const response = await fetch('https://api.github.com/users/octocat');
3
4 if (!response.ok) {
5 throw new Error(`Failed to fetch user: ${response.status}`);
6 }
7 
8 // response.json() reads the stream to completion and parses JSON
9 const userData = await response.json();
10
11 console.log('Username:', userData.login);
12 console.log('Public Repositories:', userData.public_repos);
13}

2. Response Body Streams Can Only Be Read ONCE!

A crucial architectural detail of the Fetch API is that the body stream can only be consumed once. Attempting to read it a second time throws a TypeError:

1const response = await fetch('/api/data');
2 
3const json = await response.json(); // Consumed the stream!
4// const text = await response.text(); // ERROR: TypeError: Failed to execute 'text' on 'Response': body stream already read!

The Solution: Cloning the Response

If you need to read the body multiple times (for example, for logging and parsing):

1const response = await fetch('/api/data');
2const clonedResponse = response.clone(); // Clones the stream before reading
3 
4const textDebug = await clonedResponse.text();
5const jsonData = await response.json();

3. Safe Parsing: Handling Malformed JSON & Non-JSON Responses

If a server crashes and returns an HTML error page (e.g., 502 Bad Gateway from Nginx) instead of JSON, response.json() will throw a SyntaxError: Unexpected token < in JSON.

1async function safeFetchJson(url) {
2 const response = await fetch(url);
3
4 const contentType = response.headers.get('content-type');
5 if (!contentType || !contentType.includes('application/json')) {
6 const rawText = await response.text();
7 throw new Error(`Expected JSON but received: ${contentType}. Content: ${rawText.slice(0, 100)}`);
8 }
9 
10 try {
11 return await response.json();
12 } catch (parseError) {
13 throw new Error(`Failed to parse JSON payload: ${parseError.message}`);
14 }
15}

4. Other Response Parsing Methods

Depending on the API format, Response provides multiple stream consumers:

MethodDecodes AsTypical Media Types
response.json()JavaScript Object / Arrayapplication/json
response.text()UTF-8 Stringtext/plain, text/html, text/csv
response.blob()Binary Large ObjectImages (image/png), PDFs, Audio files
response.formData()FormData Objectmultipart/form-data
response.arrayBuffer()Raw Binary BufferWebAssembly .wasm, low-level byte manipulation

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does response.json() return?
Question 2
What happens if you call both response.json() and response.text() on the same Response instance without cloning?
Question 3
Why does calling response.json() sometimes throw SyntaxError: Unexpected token '<'?
Question 4
Which method should you use on a Response object to download and display an image file?
Question 5
How can you check if the server declared the response payload as JSON?
Next Lesson

GET vs POST Requests

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Fetching Data from APIsGET vs POST Requests

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext