Accessing local JSON data through JavaScript

I am looking to access a JSON file locally using JavaScript. The file is named "posts.json" and contains the following information:

{
    "post0": "<empty>", //1
    "post1": "<empty>", //2
    "post2": "<empty>", //3
    "post3": "<empty>", //4
    "post4": "<empty>", //5
    "post5": "<empty>", //6
    "post6": "<empty>", //7
    "post7": "<empty>", //8
    "post8": "<empty>", //9
    "post9": "<empty>" //10
}

Additionally, I would like to make modifications to this JSON file within my code.

Could someone provide guidance on how to achieve this?

Thank you, Christian

Answer №1

To access information from a JSON file, you can follow this approach:

const fs = require('fs');

let data = fs.readFileSync('data.json');
let jsonData = JSON.parse(data);
console.log(jsonData);

When it comes to updating a JSON file, consider the following method:

const fs = require('fs');

let newData = { 
    "item0": "<empty>", //A
    "item1": "<empty>", //B
    "item2": "<empty>", //C
    "item3": "<empty>", //D
    "item4": "<empty>", //E
    "item5": "<empty>", //F
    "item6": "<empty>", //G
    "item7": "<empty>", //H
    "item8": "<empty>", //I
    "item9": "<empty>"  //J
};

fs.writeFile('data.json', newData, (error) => {
    if (error) throw error;
    console.log('Content successfully updated');
});

If you're interested in reading files on the client-side, consider utilizing the FileReader API:

HTML:

<input type="file" id="file" name="file" enctype="multipart/form-data"/>

JS:

document.getElementById('file').addEventListener('change', loadFile, false);

function loadFile(event) {
    var files = event.target.files;
    var chosenFile = files[0];           
    var reader = new FileReader();
    reader.onload = function(evt) {
       console.log(evt.target.result);            
    }
    reader.readAsText(chosenFile)
}

Answer №2

One limitation is that you cannot access local directory files using JavaScript. Additionally, you can retrieve files from any server, including your localhost (via web URL). Assuming your application is hosted on IIS or Node.js, the following code will function properly. Keep in mind that the URL specified here is relative to your application's root directory.

// Alias URL: http://localhost:4200/post.json
    $.getJSON( "posts.json", function( json ) {
      console.log( "JSON Data: " + json);
      console.log( "particular data Data: " + json.post0 );
     });

You can manipulate in-memory data like this and utilize it anywhere within your application


    $.getJSON( "posts.json", function( json ) {
     console.log( "JSON Data: " + json);
     json.post0 = 'Another value' );
    });

However, keep in mind that this will not update your actual file. To do so, you will need to make another AJAX call to your server-side technology (.NET, Java, or Node.js) to update the file.

Note: In this example, jQuery was used but feel free to use any appropriate technology for your needs.

Answer №3

When facing restrictions on executing script languages locally, it becomes necessary to find alternative methods for loading files from a server. One way to achieve this is by setting up a web server quickly in your local directory using the following command:

npm i http-server

After installing, run the server with:

npm http-server .

This will create a localhost:8080 where you can view your index file. From there, you can load your JSON file using either XMLHttpRequest or importing it at the top of your JS file. If you need to modify the loaded file, you can parse it using:

JSON.parse(file-content);

Answer №4

Exploring the concept of reading JSON files from a local relative path without jQuery or server coding is an interesting endeavor. Some individuals opt to embed a data string variable within the JSON file, allowing for easy reference as a JavaScript script on a webpage.

<script type="text/javascript" src="./path/to/myfile.json"></script>

This approach deviates from the traditional structure of typical JSON files and functions more like a JavaScript file. While JSON files are considered JavaScript files too, complex properties may necessitate splitting the data string across multiple lines:

data = '[' + 
  '\n{"name" : "Independence Day", "id" : "ID"}' + 
  ',\n{"name" : "Stars Wars", "id" : "SW"}' + 
  ',\n{"name" : "Star Treck", "id" : "ST"}' + 
']';

An alternative method involves structuring the JSON file in a conventional manner without the need for extensive string concatenation:

data = [
  {
    "name": "Independence Day", "id": "ID"
  }, 
  {
    "name": "Stars Wars", "id": "SW"
  },
  {
    "name": "Star Treck", "id": "ST"
  }
]

Edit the file using any standard text editor such as Notepad or Wordpad available on most operating systems. Alternatively, leverage tools like Microsoft Visual Studio Code with plugins for TypeScript interpretation to simplify the process of handling .JSON files and identifying errors.

Additionally, prior to parsing the data, introduce a stringify instruction in the .js script file:

function load() {
    var str = JSON.stringify(data); 
    var mydata = JSON.parse(str); 

    const n = mydata.length; 
    for (let i = 0; i < n; i++) { 
        alert(mydata[i].name);
        alert(mydata[i].id);
    }
}

To ensure functionality when multiple scripts are present on a main page, consider moving the load function into the main page and calling it within a separate main() function. To initiate this function upon loading, utilize the onload attribute within the html body tag.

<body onload="main()">

Declare the main() loading function in a separate script block:

<script type="text/javascript">
function main(){
load(); 
}
</script>

Add your own Script.js file as a src attribute if 'load' is the only startup function required. Testing may be necessary depending on specific conditions and needs.

While the movie list example showcases reading file content, practical applications may involve managing lists of employees or clients using JavaScript and HTML, bypassing costly software. Sensitive information remains secure as it resides locally rather than on a public server.

The primary motivation for utilizing JSON properties and methods lies in enabling access to local file contents through JavaScript due to security limitations restricting direct access via a web page. The use of input controls or drag-and-drop features can offer alternatives, providing users with flexibility in file selection.

The insights shared draw inspiration from previous Stack Overflow queries and Google searches, combined with personal experimentation. Despite working on older systems and browsers, with modest programming skills, I hope this explanation proves beneficial.

Warm regards, Adrian Brinas.

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

The AngularJS framework is not effectively generating the desired table structure

EDIT 1 - Here is a Plnkr example that demonstrates the issue - http://plnkr.co/edit/qQn2K3JtSNoPXs9vI7CK?p=preview ---------------- ORIGINAL CODE AND PROBLEM ---------------- I've been using the angular datatable library (angular-datatables) to g ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

The redirection from HTTP or www to HTTPS is not functioning as expected

Redirecting all links to my website to the https:// domain is supposed to work flawlessly, but there are certain ways it doesn't quite function as expected. https://www.example.com --- works example.com --- works www.example.com --- encounters issu ...

jQuery scrollTop animates to the start of the webpage

Upon loading the page, the div appears at the top of the screen but then jumps to its correct position once scrolling begins. To view the website, click on this link: calretirement.com/classes-test.php CSS: .register{position:fixed !important; bottom:1 ...

Tips for resolving an Angular 504 Error Response originating from the backend layer

I am currently facing an issue with my setup where I have an Angular application running on localhost (http) and a Spring Boot application running on localhost (https). Despite configuring the proxy in Angular to access the Spring Boot APIs, I keep receivi ...

Using Google Maps to Cluster Markers on Your Website

I need to display numerous markers on a map for my website. My inquiry is whether the google maps api for javascript still supports clustering for websites? I attempted using marker cluster and it seems like it's not functioning properly. If so, can ...

iterate through the ordered list (ol) elements within nested lists

I am currently attempting to convert my hierarchical list into a JSON object in the following format; [ {title: title1,id: 1,children: [ {title: title1_1,id: 1_1,children: [ {title: title1_1_1,id: 1_1_1,children: []}, ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

Ways to access a function variable within an AJAX `done` function

This is the JavaScript function I am working with: $('.editable').change(function () { event.preventDefault(); var el_text = this.lastElementChild; var action = this.action; var method = this.method; var data = $(this).serialize(); ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

Similar route with identical element

Struggling to create a file renderer in the most efficient way possible. The current snippet I have seems quite repetitive: <Routes> <Route path='/explorer' element={<Files>}> <Route path=':root' element={< ...

Tips for utilizing the vuetify readonly prop while enabling the selection menu

In my project, I have a grid containing v-autocomplete components with the multiple attribute. To maintain clean formatting, I decided to show only a shortened version of the content using the selection slot feature provided below: <v-autocomp ...

Creating Canvas dimensions to match the dimensions of a rectangle specified by the user

When the code below runs, it correctly generates a rectangle the same size as the canvas on start-up. However, an issue arises when the user clicks the button to generate a new canvas - the rectangle does not appear. Can someone please provide assistance ...

The property length is undefined and cannot be read

I'm currently utilizing a dexi.io robot for the purpose of automating data extraction from permit databases. This particular robot has the capability to process custom JavaScript in order to dissect the incoming JSON object. While this code does func ...

When working with JSON data in AngularJS, remember to utilize the ng-repeat directive to

I am working with a JSON file that looks like this: { "2014-08-01T23:00:00.000+05:30": { "In": 12, "Out": 23, "s1": 0 } "2014-08-01T22:00:00.000+06:00": { "In": 0, "Out": 0, "s2": 0 } "2014-08-01T22:00:00.000+06:30": { "In": 54, "Out": 0, "s3": 0 ...

Struggling with passing data to a child component in React

I am currently working on a gallery project where users can click on an image to view it in a separate component using props. The images are sourced from a hardcoded array, and the challenge lies in connecting this data to the component accurately. I have ...

What is the method for getting js_xlsx to include all empty headers while saving the file?

In the midst of developing a Meteor App, I've incorporated the Node.js package known as "js_xlsx" from "SheetJS", produced by "SheetJSDev". This tool enables me to convert an Excel sheet uploaded into JSON on the backend. The intention is to store thi ...

What methods does node.js use to distinguish between server-side and client-side scripts?

One interesting aspect of PHP is the ability to combine both PHP and JavaScript code within a single file. However, it raises the question: How can we incorporate both server-side and client-side JavaScript code in an HTML file? ...

The Angular JS Factory fails to send data back to the controller

When I call the method getPopularMovies in my factory using the controller, it returns undefined. I'm not sure what mistake I've made here. Please help me figure it out. My Factory angular.module('ngMovies').factory('moviesFactor ...

list of key combinations in a ul element

I programmed a list of world states in PHP using an unordered list (<ul>): $WORLD_STATES = array( "France", "Germany", "Greece", "Greenland", "United Kingdom", "United States", "Uruguay" ...