Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive.

I have managed to store the string using the following code snippet on Firefox:

function saveJSON() {
    var obj = {name:'John', max:100};
    window.open( "data:text/json;charset=utf-8," + escape(JSON.stringify(obj)))
}

However, this method only works on Firefox, and I need a solution that also works on Internet Explorer. I have looked into using ActiveX but have not been able to find a suitable example for implementation.

Should I explore the ActiveX route, or is there a more effective HTML/JS solution that is compatible with both browsers?


The second issue I am facing is loading the JSON file. After some research, I discovered that after loading the file, I can convert it into a JSON variable using JSON.parse. However, I am unsure of how to actually load a selected JSON file. I have an

<input type=file id="filePath">

element to obtain the file path (although it returns different values in each browser), and ideally I would like to perform something similar to

var a = loadFile(filePath.value)

If anyone has any suggestions or solutions for how to achieve this, I would greatly appreciate the assistance.

Thank you.

Answer №1

If you want to load a file, it has to already be present on the server. From there, you can integrate it into your script either by lazy loading or including it in the head section. Another option is using the .load() method from the jQuery AJAX library. If the file isn't available on the server, you'll need to upload it first to prevent XSS attacks.

To retrieve data from a specific point, you can utilize the .load(), .get(), or full .ajax() calls provided by jQuery. Detailed information can be found here: http://api.jquery.com/load/

For saving data, consider storing it in a cookie, submitting the data through a form to open in a new window, or passing it via query string if that's preferable for your needs.

Although I personally use a different JSON library, the following code executes successfully in both Internet Explorer and Firefox:


$(document).ready(function() {
  var obj = { name: 'John', max: 100 };
  window.open("data:text/json;charset=utf-8," + escape($.toJSON(obj))) 
})
</pre>

If you want an efficient way to pass data, try something like this function:


function saveJSON(){
  var obj = {};
  obj.name = 'John';
  obj.max = 100;

  $("#json").val($.toJSON(obj));
  $("#hiddenForm").submit();
}

Don't forget to include a simple form to hold the data:

<form action="somepageToDisplayFormFields.php" target="_blank" id="hiddenForm">
  <input type="hidden" name="json" id="json" />
</form>

This method enables you to transfer larger and more complex objects without worrying about URI size restrictions or browser compatibility issues. Additionally, dealing with functions like escape(), encodeURIComponent(), etc., can become quite frustrating over time.

Answer №2

After much searching, I stumbled upon a solution for reading client-side files that seems to be effective. The method requires user intervention and is considered relatively secure. Although it currently only functions on Firefox, I am content with this limitation for now.

I want to express my gratitude for all the valuable comments and responses provided; they have truly expanded my knowledge on this topic.

Answer №3

Performing direct file system manipulation is typically restricted in client-side JavaScript for security reasons. Would you want unknown websites accessing your files?

However, you can achieve a similar result by making your JSON data into a downloadable link - just place your DATA URL as the href of a link, which should work on IE8 and newer versions. Unfortunately, older versions of IE may not support this method.

If you need to retrieve a JSON file from a specific path, there is a Firefox-only property that allows you to do so. More information can be found at: https://developer.mozilla.org/en/DOM/File

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

Trouble fetching asynchronous data in Next.js Higher Order Component

Currently, I am in the process of creating a Higher Order Component (HOC) that will fetch user data from my API and then provide props to the wrapped component. This will allow the component to redirect the user based on their role. Although the HOC appea ...

What is the best way to retrieve a value by using the data.get() method?

I am currently facing an issue with retrieving the value of a textarea that I have dynamically added to a fieldset in my form. When I attempt to submit the form, the code below is executed: function handleSubmit(e) { e.preventDefault(); console.log( ...

What are some effective methods for troubleshooting npm modules?

Typically, the process involves installing React with yarn/npm install react and then using it by importing React from 'react' Imagine you need to debug a React source code, so you clone a GitHub repository. But how do you incorporate this sour ...

Ensuring Valid Submission: Utilizing Jquery for a Straightforward Form Submission with 'Alajax'

After searching for a straightforward JQuery plugin to streamline the process of submitting forms via Ajax, I stumbled upon Alajax. I found it quite useful as it seamlessly integrates into standard HTML forms and handles all the necessary tasks. However, I ...

Function invoking React Hook

I'm a beginner to React JS and I've been learning by working on a project. I was creating a basic e-commerce UI with items and attempting to add items to a cart, but encountered an issue. The React Hook "useStateValue" is being called in the fun ...

Efficiently sending data to a kintone endpoint with AWS Lambda and Node.js through AJAX

Greetings Stack Overflow community! I need some assistance as I am facing a challenge while trying to interact with an API to insert records into a Kintone App. My approach involves utilizing ajax to communicate with an AWS lambda function built using node ...

ReactJS - Unable to access property of undefined object

I encountered a TypeError when rendering, stating that my object is not defined. Despite thinking I defined it before using it. Here is an example of ArticleDetails.js that I am referencing: import React, {Component} from 'react'; class Arti ...

Verifying that the data has been successfully saved using JavaScript

When a user submits a small chunk of data via AJAX using a standard update action and a remote form, the information is sent to the action as javascript. The response is then rendered in javascript utilizing format.js. def update @message = Message.wher ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

Develop a video in mp4 format using Node.js and ffmpeg by combining two or more jpg images

I am currently working on a video animator project where I generate .jpg images from an html canvas tag and then use these images as frames for the video. The tool I am using for video generation is ffmpeg. Successful with Single Image const ffmpeg = req ...

A pattern matching formula to eliminate specific characters from the beginning to the end of a string

I am facing an issue with extracting content from a given string: var string = "From: Sarah<br /> Sent: 10 May 2021 09:45:20</br /> To: Alice<br /> Subject: Meeting Reminder<br /><br /> Hi Alice, <br /> Here is a ...

How can I parse a JSON string in a node.js environment?

My current challenge involves sending a JSON string and parsing it on the server-side in node js. The specific value I am trying to extract is the title, but I keep encountering undefined when attempting to parse it. This is my current approach: Home.ejs ...

Display the URL with proper formatting in the print function

I am trying to create a table with clickable URLs in a "Link" column, but the URLs are too long and I want to show a custom title instead. So far, I have used the following code: str = "Test Title"; link = str.link("https://my_long_url.com/v1.0/ui/index. ...

Creating a server that is exclusive to the application in Node.js/npm or altering the response body of outgoing requests

As I work on developing a node app, the need for a server that can be used internally by the app has become apparent. In my attempts to create a server without listening to a port, I have hit a roadblock where further actions seem impossible: let http = ...

Disable the scroll animation feature for certain IDs

I implemented JavaScript code to animate scrolling for each block with a specific ID. However, when I added Bootstrap's tabs, the animation interfered with the functionality of the tabs. Is there a way to disable the scroll animation specifically for ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

Using props as classnames in next.js applications

I am currently attempting to create a dynamic header for each page of my app that changes color based on the current page. Here is my approach: <Header className="headerBitcoin"></Header> My goal is to have the same header component ...

Issues Persist with Updating mySQL Database using PHP

I've been attempting to insert location data into a MySQL database using my PHP server from the TripTracker Android App. However, despite trying different approaches in PHP, I have not been successful so far. Any assistance would be much appreciated. ...

Encountering the issue: receiving an error message stating that shuffle(...) is undefined within

Whenever I try to add it into the app.js file, it keeps coming up as undefined. app.js (function () { var tkcApp = angular.module('TKC', []); var shuffle = function (o) { for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = ...

embedding a button alongside the pager in an HTML document

I am encountering an issue with the positioning of a button in my paginated table setup. The button is currently displaying below the pager instead of being aligned on the left side of the page along with the pager. https://i.stack.imgur.com/gUiB9.png To ...