Are you utilizing Google Chrome extensions for importing and exporting JSON files?

Currently, I am in the process of developing a Google Chrome extension and I have a question regarding its capabilities. Is it possible for the extension to generate JSON files for users to download (export) as well as implementing a button that allows users to open and parse JSON files stored locally or on a USB stick (import)?

The process of parsing each JSON file from the local system would involve extracting key-value pairs and performing some actions with the data. This operation would be limited to dealing with strings only, making it relatively straightforward.

**EDIT:** In reference to my query, it differs from this one because my focus is not on altering the user's download path. My intention is solely to provide an option for users to download a file to their normal directory with their permission (which Filesaver.js can facilitate). Additionally, the linked post does not address the concept of importing files.

Answer №1

To create a faux link to "download" an imaginary array called MyData, follow these steps:

var MyArray = [elem1, elem2, ....];
var _myArray = JSON.stringify(MyArray , null, 4); //indentation in json format for clarity

var vLink = document.createElement('a'),
vBlob = new Blob([_myArray], {type: "octet/stream"}),
vName = 'custom_filename.json',
vUrl = window.URL.createObjectURL(vBlob);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
vLink.click();

This code will allow you to export/download your array into a json file named as specified in the vName variable.


If you want to import/read a file:
create an input element of type file and hide it (below is the HTML element followed by a JavaScript listener)

<input type="file" id="importOrig" accept=".json" style="display:none"/>

JavaScript section

importOrig.addEventListener("change", importFun, false);

Create a button or any element, like fakeImp, that can be styled and used as a trigger for importing event

fakeImp.onclick = function () {importOrig.click()}

Function for importing data (from the listener)

function importFun(e) {
  var files = e.target.files, reader = new FileReader();
  reader.onload = _imp;
  reader.readAsText(files[0]);
}

function _imp() {
  var _myImportedData = JSON.parse(this.result);
  //here is your imported data, you can proceed to save it to storage or perform other actions

  ......
  importOrig.value = ''; //clear input value after each import
}

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

Ensuring Data Integrity with JavaScript Form Validation

Ensure that if text box A is filled in, text box B must also be filled in before submitting. Vice versa, if text box B is filled in, make sure text box A has data as well. Is it possible to loop this check for multiple text boxes? For example, if row A o ...

What is the best way to combine nested values into a single column using tidyjson?

Is there a way to combine two values into one column instead of spreading them? '{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>% spread_values( first.name = jstring("name", "first"), age = jnumber("age") ) %>% unite(conc, c("f ...

Retrieve the class name based on the ID of the final appearance of the div using jQuery

<div class='user user1' id='newuser'></div> <div class='user user2' id='newuser'></div> <div class='user user3' id='newuser'></div> To retrieve the class name ...

Tips for showcasing Markdown files within subdirectories in Next.JS

In my Next.JS project, I am managing numerous Markdown files that are organized into various category folders. For example, I have folders named 'CategoryOne' and 'CategoryTwo' located at the root level of the project alongside node_mod ...

Problems with accessing Ajax login

I'm encountering issues with an Ajax login function. Despite finding a similar question that didn't help, I'm still unsure of the problem. It's perplexing because this code functions without any problems in another project. Hopefully, ...

Step-by-step guide on transforming jQuery code into Vue JS:

Recently delving into Vue, attempting to translate previous JS + JQuery code into Vue Here is the list I'm working with: <ul id="progressbar"> <li class="active">integration Ip's</li> <li>T ...

Executing a JS function within a table cell

I've been attempting to invoke a function within a table cell to dynamically create some data, but I keep encountering this error below. I'm uncertain whether I'm correctly calling defined functions and JavaScript functions inside the table ...

Expanding a list of object arrays through iteration: A step-by-step guide

// Initializing with one object let posi_val=[{top: '3px', left: '2px'}]; // Adding another object in the loop for (let i = 1; i < n; i++) { posi_val.push({ top: `${posi_val[i - 1].top.slice(0, -2) * 2}px`, l ...

The Nuxt image keeps disappearing every time I navigate to a new page

Whenever I have an image displayed on my Nuxt page and then navigate away from it, the image breaks and I can't figure out why. This is what my code looks like: <img :src="baseUrl + 'storage/'+ front.featured_image" alt="p ...

Remove option from MUI Autocomplete after it has been selected

I am currently utilizing a Material-UI Autocomplete component. To avoid users selecting the same element twice, resulting in duplicate ID numbers, I want to remove the element from the dropdown entirely. For instance, if "Shawshank Redemption" is selected ...

Printing using *ngFor will display items in an ascending order

When attempting to display an object in markup, I am running into the issue of *ng printing it in ascending order instead of maintaining the original order. Ideally, I would like the elements to be printed as they are. You can view my code on StackBlitz ...

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...

Excessive Usage Alert on Nest Thermostat - Response Code 429

I came across this amazing Google Script on Github at https://gist.github.com/beezly/9b2de3749d687fdbff3f, which I use to retrieve the temperature from my Nest thermostat and record it in a Google Spreadsheet. Everything works perfectly when I manually ex ...

What is the best way to implement a date range filter in AngularJS for a specific year or month?

I am just starting to learn AngularJS. I have a date formatted as follows: d MMM y. However, I have two fields - one called "from" and the other "to" - that should act as filters for the date range, based on a year range or month range. Here is how I am or ...

Transform the appearance of a button when focused by utilizing CSS exclusively or altering it dynamically

As a newcomer to coding, I am currently working on a project that involves changing the color of buttons when they are clicked. Specifically, I want it so that when one button is clicked, its color changes, and when another button next to it is clicked, th ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Two select boxes trigger multiple sorting operations

Struggling to implement 2 different sorting operations on two separate columns in a datagrid, using 2 different select boxes has proven to be challenging. I attempted the code below, but as a beginner, I was unable to solve it... In HTML: <select ng ...

Regular Expression for jQuery to match both letters and numbers, including special characters

Is there a way to validate text input using a jquery regex that includes specific characters such as A-Z, a-z, 0-9, !, #, $, £ (preferably all currency characters), %, &, -, and _? If so, how can this be implemented? I have attempted to use the regex pa ...

Understanding the JSON output received from the Servlet

So, I have a Java Servlet set up to return JSON data in Application/JSON format using the GSON library. The GET method of the Servlet requires an ID parameter. When I send a request with BookingID as 1, Chrome shows the AJAX response like this: 0: {W ...

What is the best way to showcase my customized license plate on the following page?

I need help with incorporating my number plate builder into a website. I have utilized JQUERY and JAVASCRIPT for the styling aspect, but now I want to display the designed plate on the next page. Can someone guide me on how to achieve this using PHP, JQUER ...