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?
- JSON (JavaScript Object Notation): A lightweight format for storing and transmitting data. It uses key-value pairs to represent structured data.
- Blob (Binary Large Object): A Blob represents a raw data object that can hold various types of data, including text, images, or even audio.
Below are the methods for converting JSON data to a Blob object:
Table of Content
- Using JSON.stringify and Blob constructor
- Using fetch API (for pre-existing JSON data)
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:
- Use the first method if you have the JSON data as a JavaScript object.
- Use the second method if you have the JSON data stored remotely as a file accessible through a URL.
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.
Contact Us