Access JSON file from local PC within a Nativescript application

I am struggling to display the contents of my JSON file in Nativescript using console commands. My goal is to showcase these contents and leverage the values in the file to perform additional functions.

Here is the Javascript function that I have tweaked slightly from NS documentation and Emil Oberg's solution on a different thread:

var fs = require('file-system');
var documents = fs.knownFolders.documents();
var jsonFile = documents.getFile('/Users/student/Desktop/Native_Script/Library/app/images/status.json');
var array;
var jsonData;

jsonFile.readText()
.then(function (content) {
    try {
        jsonData = JSON.parse(content);
        array = new observableArrayModule.ObservableArray(jsonData);
    } catch (err) {
        console.log(err);
    }
    console.log('Item:' + JSON.stringify(jsonData));
});

////////////////


JSON File:
[{
    "Status": "3",
    "Trend": "increase",
    "Space": "Gleason"
}, {
    "Status": "2",
    "Trend": "decrease",
    "Space": "PRR"
}, {
    "Status": "4",
    "Trend": "stable",
    "Space": "WBR"
}, {
    "Status": "1",
    "Trend": "decrease",
    "Space": "HCR"
}]

If anyone can point out where I might be making a mistake and advise me on how to display any component of the file in the console, I would greatly appreciate it. The main objective is to utilize one of the values in the file, such as status, to invoke another function.

For instance, something along the lines of: (pseudocode)

status.getvalue .then(function) if status > 3 console.log(place is crowded)

Answer №1

If you're attempting to access a file on your computer from a mobile device such as an iPhone, Android, or Emulator, that's not possible with the getFile call. This function requires a path specifically on the device itself.

Here are two options:

  1. Save the JSON file directly onto the device.
  2. Use require() to access the JSON file. For example, you can use
    var jsonFile = require('status.json')
    for it to be read and parsed automatically.

Answer №2

If your jsonFile.readText() is causing an error, consider adding the following code snippet:

p1.then(function(result) {
  console.log(result); // "Success!"
  throw 'oops!';
}).catch(function(error) {
  console.log(error); // "oops!"
})

jsonFile.readText()
    .then(function (data)
      {
        try {
        jsonData = JSON.parse(data);
        //console.log('Item:' + JSON.stringify(jsonData));
        array = new observableArrayModule.ObservableArray(jsonData);
       }   
       catch (exception) {
       console.log(exception);
       }
       console.log('Item:' +JSON.stringify(jsonData));    
   })
  .catch(function(error) {
      console.log(error); // "oops!"
    });

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

Actions for jQuery's mouseenter and mouseleave events

I've implemented a jQuery script that controls the visibility of elements based on mouse events: $("#divid").mouseenter(function() { $('#divid').show(1000); }).mouseleave(function() { $('#divid').hide(1000); }); $("#hldiv" ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

The mesh takes on a more defined geometric shape once it has been processed using ThreeCSG

When I use ThreeCSG to subtract one mesh from another, I encounter a problem. The main mesh is a ring and the mesh to subtract is a diamond. Initially, the scene looks fine: Mesh fine. However, after subtracting the meshes, the ring become angular: Mesh Br ...

Extending error handling in Node.js fs module

In the server-side file moving utility, if the target directory does not exist, the error returned is as follows (over the wire): {errno: -2, code: 'ENOENT', path: 'uploads/workgroup/message.docx'} The code snippet on the server side ...

How can the vertical scroll bar position be reset in Material-Table when pagination is activated?

Whenever I scroll up or down in my Material-Table, and then switch pages, the vertical scroll bar doesn't reset to the top of the table. Instead, it stays where it was before changing the page, causing confusion for users. The only mention of scroll ...

Converting a hierarchical JSON structure containing arrays into a flat CSV file with the ability to apply

I have a query regarding the usage of Powershell to flatten a nested JSON and convert it into CSV format. Here is a sample JSON data representing mail message logs retrieved from Office 365, containing messages from multiple users. I need to filter the col ...

Adding Axios package to a Vue 3 project without using the CLI

I'm facing an issue while trying to integrate the Axios package into my Vue 3 project that is not CLI-based. I initially attempted to include the package within the script tags at the top of the page, but that approach failed. Next, I tried creating a ...

Populate the div with the URL parameter only when another span element is empty after a specified time interval using setTimeout

When displaying a person's name on a page, there are two different methods to consider. It can be extracted from the URL or retrieved from an email form in the CMS used. However, these two approaches sometimes conflict with each other. Currently, I h ...

Mobile devices experiencing issues in loading Javascript scripts

Let me start by sharing my JS code: function getTimeRemaining(endTimeInput) { var endTime = new Date(endTimeInput); var currentTime = new Date(); var t = endTime - currentTime; var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 100 ...

Using the split and join methods in PHP for Javascript operations

Can you assist me with writing this code in PHP? I've attempted multiple times but I can't seem to get it right. Any help would be greatly appreciated! return s.split(/\r?\n/).join("<br>"); Thank you in advance! ...

loading the css and javascript files based on the specified prop parameter

In the process of working on a ReactJS file that utilizes the react-ace library, I currently have the following code implemented. import React, { Component } from 'react'; import 'brace/mode/html'; import 'brace/theme/monokai&apos ...

When implementing JWT for route authentication, the webpage remains frozen in one spot

Currently, I am in the process of making modifications to a project. The front-end is built using Vue 2.0 and the back-end utilizes Node.js Express. To ensure security, I have implemented the JWT approach by requiring authentication for all pages except th ...

Adding the classname "active" in ReactJS can be achieved by utilizing the `className` attribute within

I am facing an issue with adding the active classname in my code. Can anyone suggest a solution to add the active classname for this section: <li onClick = {() => onChangeStatus({status: 'on-hold'})} className = {appState === {'status& ...

How can I design a trapezoid with see-through borders and background?

Using various CSS border tricks, it's possible to create a trapezoid shape. Additionally, setting the border-color to rgba(r,g,b,a) can make it transparent. However, is there a way to create a trapezoid with both transparent borders and background? ...

Triggering a postback event with an alert upon confirmation in an ASP.NET button

Encountering an issue with the javascript alert in my ASP.NET application. I have a button that deletes a user from the database. However, users may have associated documents and insurance policies. I want to trigger a javascript alert if the user has an ...

Tips for using jQuery to add several image source URLs to an array

My JavaScript code uses jQuery to collect all image sources on document load and store them in an array: var sliderImg = []; sliderImg.push($('.thumbnail').children('img').attr('src')); Then, I have a click event set up to a ...

Json does not retain the data from the input file

Greetings! I just finished creating a form that looks like the following: <form method="post" Action="Save.php" enctype="multipart/form-data"> <label>Name:</label><br><br> <input name=" ...

What is the best way to format and return a result object list in JavaScript or Angular?

I have a question regarding the use of for loops in JavaScript or utilizing Angular to output the resulting object list. Here is an example of an object list: var alist = []; alist = [ { 'code': 1000, 'type': 'C' ...

Present the selected values in the correct manner

My app uses a select tag to add values in a table. This select allows me to choose one value and add it to the table. Here is some of the code for the select input: const searchPlayer = selectedItems => { selectedItems = selectedItems.map(name =& ...

Update the button label using data from a JSON source

While I am iterating through my JSON data, I want to dynamically set the button title based on the JSON property title. How can I achieve this? func getDataFromJSON(){ //Calling getCollectionViewData from the RestParser class RestParser.sharedInst ...