Open In App

How to Convert JSON to Blob in JavaScript ?

This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data.

What is JSON and Blob?

Below are the methods for converting JSON data to a Blob object:

Using JSON.stringify and Blob constructor

This approach involves stringifying the JSON object into a human-readable format and then creating a Blob object from the string.

Example: This example shows the use of the above-explained approach.

const {Blob} = require('buffer');
const jsonData = { name: "Example Data", value: 10 };

// Stringify the JSON object
const jsonString = JSON.stringify(jsonData);

// Create a Blob object with the JSON string and 
// set the content type as "application/json"
const blob = 
    new Blob([jsonString], { type: "application/json" });

// Blob object representing the JSON data
console.log(blob); 

Output
Blob { size: 34, type: 'application/json' }

Using fetch API (for pre-existing JSON data)

If you already have the JSON data as a URL, you can use the fetch API to retrieve it and then convert it to a Blob object.

Example: This example shows the use of the above-explained approach.

const jsonUrl = "https://example.com/data.json";

fetch(jsonUrl)
  .then(response => response.blob())
  .then(blob => {
    console.log(blob); // Blob object containing the downloaded JSON data
  })
  .catch(error => console.error(error));
}


Choosing the Right Method:

Conclusion:

By following these methods, you can effectively convert JSON data into Blobs for further processing or download in your JavaScript applications. Remember to specify the appropriate content type ("application/json") when creating the Blob to ensure correct data interpretation.

Article Tags :