A guide to effortlessly importing JSON data with Svelte

During my recent testing, I have successfully utilized the below code to work with a component:

<script>
import x from "/path/to/x.json"
</script>

This code snippet effectively loads the json file into the variable x.

Now my objective is to dynamically load a local JSON file based on user input from an <input> element. For example:

<script>
let files ;
function loadJSONFile(){
  doSomething(files[0].name) ;
}
</script>

<input type="file" bind:files on:change={loadJSONFile}>

In this scenario, the function doSomething() will perform a similar task as the initial import. However, it allows for loading JSON data from any local directory. The concern arises with the relative path provided by files[0].name through bind:files, which may not suit our requirement for absolute paths.

Answer №1

If you want to read a file provided by the user, you have two options - either use the FileReader API or the more recent text() function from the Blob prototype. The ideal event to trigger this action would be the change event.

(In case the user decides to cancel the dialog, all selected files will be cleared.)

<!-- utilizing .text() -->
<script>
    let jsonData;
    
    async function onFileChange(e) {
        const selectedFile = e.target.files[0];
        if (selectedFile == null) {
            jsonData = null;
            return;
        }
        
        jsonData = JSON.parse(await selectedFile.text());
    }
</script>

<input type=file on:change={onFileChange} accept=".json"/>
<pre>{JSON.stringify(jsonData, null, '  ')}</pre>

REPL

<!-- using FileReader approach -->
<script>
    let jsonData;
    
    async function onFileInputChange(e) {
        const selectedFile = e.target.files[0];
        if (selectedFile == null) {
            jsonData = null;
            return;
        }
        
        jsonData = await readFileAsJson(selectedFile);
    }

    function readFileAsJson(file) {
        const reader = new FileReader();
        return new Promise((resolve, reject) => {
            reader.onload = () => resolve(JSON.parse(reader.result));
            reader.onerror = reject;
            reader.readAsText(file);
        });
    }
</script>

<input type=file on:change={onFileInputChange} accept=".json"/>
<pre>{JSON.stringify(jsonData, null, '  ')}</pre>

REPL

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

Issue with detaching Ember and jQuery plugins

I have encountered an issue in my Ember app while attempting to update the DOM by detaching an element and appending it elsewhere. var comp = Ember.$(this.element).detach(); Ember.$("#some-sec").append(comp); After performing this operation, the previous ...

Displaying a Jquery slider by clicking on links

I am interested in setting up a slider for two different forms. Specifically, I plan to have one form labeled Form 1 and another labeled Form 2 displayed as text. When users click on Form 1, a table containing the form will slide out from underneath the ...

AngularJS array value with HTML tags is not displaying properly upon invocation

In Angular, I have an array that has the following structure: $scope.posts = [ { "ID" : id(), "Title" : "A", "Company" : "Company A", "Location" : "San Francisco, CA", "Date" : "2016-06-20", "Description ...

The Ajax request functions correctly in Chrome and Safari but encounters issues in Firefox and Internet Explorer

I've encountered an issue with jQuery where the call is failing when making a request with base64 authorization header in the beforeSend function. It's a simple request to retrieve projects. function GetProjects(full){ var query = "/Projects"; $ ...

Executing a Jquery click event after a delay with setTimeout

I am working with an <a> element that, when clicked, triggers a handler like this: function onCummReportClick(e) { if ($(e.currentTarget).attr('href').indexOf('csv') !== -1) { { return true; } //Here s ...

How to deactivate or modify the href attribute of an anchor element using jQuery

My HTML code looks something like this: <div id="StoreLocatorPlaceHolder_ctl07_ctl00_ctl00_pager_ctl00_ctl00_numeric" class="sf_pagerNumeric"> <a href="http://www.domain.com/store-list">1</a> <a href="http://www.domain.com/sto ...

Using two onMouseOver functions in React.js

render: function() { return ( <td> <img src={this.props.image.path} width="40" height="40" id={this.props.image.id} onMouseOver={()=>document.getElementById(this.props.image.id).height="80", ()=>d ...

Convert the JSON data into an array and store it in the variable

My JSON data is quite extensive which includes the following entries: {"createTx": { "inputs": [{ "address": "mtFYoSowT3i649wnBDYjCjewenh8AuofQb", "value": 0.00009 }], "outputs": [{ "address": "mmskWH7hG9CJNzb16JaVFJyWdgAwcVEAkz", " ...

Automatically numbering text boxes upon pressing the enter key

Is there a way to automatically number textboxes when I type "1" and hit enter in one of them? For example, if I have 3 textboxes and I type "1" in the first one, can the other textboxes be numbered as 2 and 3 accordingly? <input type="text&qu ...

Disable ESLint's "no-undef" rule for a specific folder when using Jest

Currently, I am using jest for testing my api calls. In addition, I utilize eslint to validate my test codes. However, since jest does not require explicit definition of methods such as test() or expect(), when running eslint, I encounter errors like: ...

Enable browser caching for form data when using AJAX to submit

I'm currently working on a web application that relies heavily on AJAX to submit form data. However, I've encountered an issue where I want the browser to cache the user's input for auto-completion in future form fillings. While I know I cou ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...

Obtaining JSON data through AJAX requests from different domains may result in receiving a JSON string format

I have encountered an issue with my cross-domain AJAX call. It seems that instead of receiving a JSON object as expected, I am getting a string from the API provider. Here is the code snippet for my AJAX request. $.ajax({ async: false, ...

Text extracted from a JSON array

I have developed an API in PHP to create a customer, with the client side being in Android using a POST request to access the API. During testing, I utilized Chrome Postman and inputted post data as follows: {"name":"test","marks":["12","13","16"],"age":1 ...

Json encoding of Php array is not functioning as expected

My ajax connection to the json.php file is not working. Do you have any idea what could be causing this issue? Is it possible that my $output variable is not convertible to JSON or could it be a problem with my ajax setup? Any help or insights would be gre ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

The click event fails to provide $event upon being clicked

Within my HTML structure in an angular 7 application, I have the following setup: My goal is to trigger the GetContent() function when any text inside the div is clicked. Strangely, when clicking on the actual text, $event captures "Liquidity" correctly. ...

Eliminating choices from a dropdown list using jQuery

I am currently working on a page that contains 5 dropdown menus, all of which have been assigned the class name 'ct'. During an onclick event, I want to remove the option with the value 'X' from each dropdown menu. My current code snipp ...

Attempting to modify the background color of an iFrame in Internet Explorer

I am experiencing an issue with my webpage where the iFrame is displaying with a white background in IE, while it shows up with a blue background in Firefox and Chrome. I have attempted various solutions to make the background of the iframe blue or transpa ...

Guide to retrieving the compiled HTML content of a Vue.js component

I have a component structured like this <AgentCard :agent="agent" />, with the object agent containing properties such as FirstName, LastName, Recent Orders, and more. My current challenge involves displaying this component inside a Google ...