dlowlad the json fiel in react js pretty formate
How to Download and Format JSON files in React JS
Introduction
As a React JS developer, having the ability to format JSON files in a readable and easily understandable manner is essential. This is where the "pretty format" comes in. In this blog post, we will discuss how to download and format JSON files in React JS using the "pretty format" method.
Step 1: Download the JSON File
The first step is to download the JSON file that you want to format. You can use various methods to download the file, such as using an API call or importing it from a local file. Once you have the file, you can proceed with formatting it.
Step 2: Install the Needed Dependencies
In order to format the JSON file, we need to install two dependencies: "prettier" and "highlight.js". You can do this by running the following command in your terminal:
npm install prettier highlight.js
Step 3: Create a Function to Format the JSON File
The next step is to create a function that will format the JSON file. This function will use the "prettier" dependency to format the file with proper indentation and line breaks. Here is an example of such a function:
function formatJson(json) {
return JSON.stringify(JSON.parse(json), null, 4);
}
Step 4: Display the Formatted JSON File
Finally, we need to display the formatted JSON file on our React JS application. We can use the "highlight.js" dependency to achieve this. Here is an example of how to display the formatted JSON file:
{
<div className="json">
<pre>
<code
className="json"
dangerouslySetInnerHTML={{
__html: hljs.highlight(
"json",
formatJson(JSON.stringify(json, null, 2))
).value,
}}
/>
</pre>
</div>
}
Alternative Method: React JSON Pretty
Another way to format JSON files in React JS is to use the "react-json-pretty" library. This library allows you to format and display JSON files with ease. Here is an example of how to use it:
import ReactJson from "react-json-pretty";
function JsonExample() {
const json = {
foo: "bar",
nested: {
hello: "world",
},
};
return <ReactJson data={json} />;
}
Conclusion
In conclusion, formatting JSON files in React JS is an essential skill that every developer should have. With the above methods, you can easily download and format JSON files in a readable and easily understandable manner. Remember to install the necessary dependencies, create a function to format the JSON file, and display it on your React JS application with the "highlight.js" dependency or the "react-json-pretty" library.