Storing JSON information on a webpage with Javascript

I am currently working on creating a local webpage using JavaScript/HTML that is meant to be opened from my computer's files. My goal is to have it store data in JSON format. However, I have been facing challenges in figuring out how to enable a local JavaScript program to read and write to a file within its own directory.

Answer №1

If you're working with Javascript in the browser, it's important to note that writing files directly to the local machine is not allowed. However, a workaround is to download a JSON file to your computer using the Blob method.

You can achieve this by implementing the following code snippet:

const data = { 
    key: "value"
};
const fileName = "data.json";

const saveFile = (() => {
    const a = document.createElement("a");
  document.body.appendChild(a);
  return (data, filename) => {
    const json = JSON.stringify(data);
    const blob = new Blob([json], { type: "application/json" });
    const url = window.URL.createObjectURL(blob);
    
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
  }
})

saveFile(data, fileName);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choosing multiple items using ng-checked and ng-model in AngularJS

I am working with an Ionic application and encountering a minor issue, much like AngularJS. <ion-list class="list-inset subcategory" ng-repeat="item in shops"> <ion-checkbox class="item item-divider item-checkbox-right" ng-model="selectAll" ...

Tips for receiving a post response following a 500 internal server error in AngularJS

I am encountering a 500 Internal Server Error when I try to make a post service call. Despite having an interceptor set up to open a dialog, the dialog appears empty. The error seems to be preventing me from receiving the response of this call, but I can v ...

Retrieving information in JSON format

My goal is to retrieve data from the info.php file in order to utilize it in my project. This is what the content of info.php looks like: <?php $dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', ''); $sth = $dbh ...

Alternating Text Color jQuery Sequencing

I'm having trouble deciding on the most effective approach to achieve this task. My goal is to animate the color change of a div's text in a specific sequence (e.g., #000, #eee, #fff...) every 1.5 seconds. From my research, I gather that I will ...

Utilizing ng-class in AngularJS based on the specific html elements

I am displaying each item from my array as an HTML paragraph using the ng-repeat directive. <p ng-repeat="item in queries track by $index">{{ item }}</p> The output looks like this: ------------ title 1 -------------- content 1 ------------ ...

Tips for removing arrays and their values when a duplicate id is detected

Is there a way to remove or filter out subsequent arrays and their values if a duplicate id is found in the previous array? For instance: const a1 = ["id1", "b", "c", "d", "e"], a2 = ["id2", ...

Encountering issue: Unrecognized parameter "id" in the "user" field of type "Query" [GraphQL, Relay, React]

We are currently setting up a query in relay. Our user database is structured like this: function User(id, name, description) { this.id = id.toString() this.name = name this.description = description } var users = [new User(1, 'abc', &a ...

Tips for sending a parameter within a JavaScript confirm method?

I currently have the following code snippet in my file: <?php foreach($clients as $client): ?> <tr class="tableContent"> <td onclick="location.href='<?php echo site_url('clients/edit/'.$client->id ) ?>&ap ...

Display the debugging result of the textarea JavaScript input in the innerHTML paragraph as "undefined"

I have been working on a code editor and I almost have everything functioning properly. I can type text into the textarea and then press a button to load a function, which displays the result of the code in the web browser console. I am attempting somethin ...

Calculate the total of the provided HTML element's content with Angular version 1.x.x

Looking to calculate the total of all values in table cells with ng-model. However, it is treating the values as strings instead of numbers. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <ta ...

What is the best way to create a full bleed background image that adjusts to different screen resolutions using CSS and JavaScript?

Similar Question: Full Screen Background Image in Firefox Check out: Is there a way to achieve a similar effect on a website where the content adjusts to different monitor resolutions? On the Ingress site, it seems like everything scales proportional ...

Is there a method to verify the type of user (user and supplier) in React without using any token, and redirect to a different page based on the API response?

Is there any way or solution to authenticate the response JSON result without token authentication? I have a project with two types of users (user=1 and supplier=2). Each user should be directed to a different page upon logging in. The JSON response looks ...

Ways to access the scrollTop attribute during active user scrolling

I've been working on a website that utilizes AJAX to keep a chat section updated in real-time. One issue I encountered was ensuring the chat automatically scrolled to the bottom when a user sent a message, but remained scrollable while new messages we ...

Altering the hue of a picture

Looking to alter the color of an image on a webpage, specifically a carport. It's crucial that the texture and shadows remain consistent. Swapping out images with different colors would require an excessive amount of images, so I'm seeking advice ...

The linkType setting from MiniCssExtractPlugin and html-webpack-link-type-plugin both seem to be malfunctioning

I have provided my webpack configuration details below: const LinkTypePlugin = require('html-webpack-link-type-plugin').HtmlWebpackLinkTypePlugin; const path = require('path'); const webpack = require('webpack'); const FileMan ...

Dealing with an unspecified parameter can be tricky - here's how you

Currently, I am in the process of developing an angular application. In this project, there is a specific scenario that needs to be handled where a parameter is undefined. Here's a snippet of my code: myImage() { console.log('test') ...

I am having trouble getting the hamburger menu to open on my website with Bootstrap. Can anyone help me troubleshoot this issue and find

Why isn't my navbar hamburger menu opening on smaller screens? Despite the links displaying correctly on larger screens, I am unable to get the navbar to open. I've tried various troubleshooting methods such as changing tags in the header, deleti ...

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

What is the reason behind TypeScript's decision not to raise an error in case of a mismatched function argument type?

Here's a simple illustration to showcase my point: type Info = { id: number; } type ImportantInfo = { id: number; value: 5; } type Task = (data: Info) => void; const task: Task = data => null; const data: ImportantInfo = { i ...

Tips for troubleshooting event listener in background.js within a Chrome extension

What is the most effective method for testing an event listener code in background.js within a Chrome extension without a user interface? Imagine you have the following background.js: chrome.runtime.onMessage.addListener(request => { console.log(r ...