Exploring JSON Data with NativeScript

As a newcomer to NativeScript and JSON, I am currently facing challenges in accessing data from my JSON file. My main goal right now is to simply log some of the data for debugging purposes.

Below is the code snippet from my view-model:

var config = require("../../shared/config");
var fetchModule = require("fetch");
var ObservableArray = require("data/observable-array").ObservableArray;

function StandingsListViewModel(items) {
var viewModel = new ObservableArray(items);

viewModel.load = function() {
    var url = config.apiURI + "getStandings.cfm?weekid=397";
    console.log(url);
    return fetch(url)
    .then(handleErrors)
    .then(function(response) {
        console.log(response.json());
        return response.json();
    })
    .then(function(data) {
        console.log("hit");
        data.Result.forEach(function(standing) {
            console.log(standing.place);
            console.log(standing.username);
        });
    });
};

return viewModel;
}

function handleErrors(response) {
if (!response.ok) {
    console.log(JSON.stringify(response));
    throw Error(response.statusText);
}
return response;
}

module.exports = StandingsListViewModel;

Here is an excerpt from the JSON file that I am working with:

{
    "hiding": 0,
    "lastupdate": 1474481622,
    "refresh": 600,
    "showmax": 0,
    "showtie": 1,

    "displayColumns" : [
        "Points"
        ,"Wins"
        ,"TieDif"

    ],
    "users" : [

        {
            "memberid" : 910089, 
            "username" : "THE DAILY ROUTINE",
            "last_entry" : "1473446820", 
            "place" : "1",
            "record" : [
            "1.0"
            ,"1"
            ,"10.0"

            ]
        } , 
        {
            "memberid" : 2234158, 
            "username" : "MR. MANAGER",
            "last_entry" : "1473277680", 
            "place" : "2",
            "record" : [
            "1.0"
            ,"1"
            ,"26.0"

            ]
        } 
    ] 
}

If anyone could provide guidance on this basic issue, it would be greatly appreciated.

Answer №1

It seems like you may be receiving the data, but not properly logging it for visibility. Instead of using:

console.log(response.json());

try using

console.dump(response.json());

The dump method outputs JSON, while log logs a string. Make sure to either stringify your JSON or use console.dump.

If that solution doesn't work, consider setting your headers as shown below:

return fetchModule.fetch(config.apiUrl + "getStandings.cfm?weekid=397", {
    method: "GET",
    headers: {
        "Content-Type": "application/json",
    }
})
.then(handleErrors)
.then(function(response) {
    return response.json();
})
.then(function(data) {
    console.dump(data)
    return data;
});

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

When using React.js with Leaflet, ensure that the useEffect hook is only run on Mount when in the

I have encountered an issue where I need to ensure that the useEffect Hook in React runs only once. This is mainly because I am initializing a leaflet.js map that should not be initialized more than once. However, anytime I make changes to the component&a ...

When clicked, the onClick feature will reduce the number each time instead of initiating the timer

Currently, I am working on a meditation application using React. As a starting point, I implemented a 25-minute countdown feature. The challenge I am facing is that the timer starts counting down each time the button is clicked, rather than triggering it ...

Tips for validating a text field in React Material UI depending on the input from another text field

Currently, I am working with Material UI TextField and encountered an issue where I need to create a code that establishes a dependency between two textfields. For example, if I enter the number 4 in textfield one, then the number in textfield two should ...

Tips for asynchronously modifying data array elements by adding and slicing

I am facing an issue in my vuejs application where I need to modify an array of items after the app has finished loading. My current setup looks like this: var n = 100; var myData = []; function loadMovies(n){ // async ajax requests // add items to ...

ESLint has detected an unexpected use of an underscore in the variable name "__place". Avoid using dangling underscores in variable names to follow best coding practices

I received the JSON response shown below. To validate the _place, I used responseData.search[0].edges[0].node._place { "data": { "search": [ { "_place": "SearchResultItemConnection", "edges": [ { "cursor": ...

How should I integrate my JS authentication function in Rshiny to enable the app to utilize the outcome?

Currently, I have an Rshiny application set to be published on the server but in order to ensure that a specific user has access, we require an API authentication token. The process of authentication is handled within JS tags outside of the application, wh ...

Enhance the Material UI Data Grid by customizing the toolbar's default slots with the option to disable the

https://i.stack.imgur.com/0YV9m.png Background In my current project, I am utilizing the Datagrid component from MUI [email protected]. I have disabled the column menu to display the toolbar at the top of the table instead of on individual columns. ...

Pressing the shortcut key will activate the function specified in ng-click,

I have been searching for a solution to my problem, but I haven't found anything that really helps. What I am looking for is a shortcut within an ng-click directive where there is only an if condition without an else expression. Essentially, I just wa ...

Parsing text files with Highcharts

As a beginner in JavaScript and HighCharts, I am facing a simple problem that has me completely lost. My goal is to generate a scatter chart with three lines by reading data from a text file formatted like this: x y1 y2 y3 1.02 1.00 6.70 ...

Converting an array of objects into an array of Objects containing both individual objects and arrays

I am dealing with an object const response = { "message": "story records found successfully", "result": [ { "created_AT": "Thu, 13 Jan 2022 17:37:04 GMT", ...

Capture the 'value' of the button when clicked using ReactJS

I'm generating buttons dynamically using the map function to iterate through an array. Each button is created using React.createElement. ['NICK', 'NKJR', 'NKTNS'].map(function (brand) { return React.createElement(' ...

Taking a Symfony approach to handling actions that return a JSON response

Utilizing PHP and CURL, I am retrieving data from a server in one of my actions and then returning the data in JSON format. The code for my action is as follows: public function executeTest(sfWebRequest $request) { $json = $this->getServerResponse ...

Is there a way to switch between showing and hiding all images rather than just hiding them one by one?

Is there a way I can modify my code to create a button that toggles between hiding and showing all images (under the user_upload class), instead of just hiding them? function hidei(id) { $('.user_upload').toggle(); Any suggestions would be grea ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

A guide to dynamically extracting values from JSON objects using JavaScript

I have a JSON array with a key that changes dynamically (room number varies each time I run the code). My goal is to access the inner JSON array using this dynamic key. Here's what I've attempted so far, but it's throwing an error. Here is ...

Utilizing MongoDB Data in an .ejs Template Using Node.js Express

After going through numerous tutorials, I find myself stuck at a point where I am struggling to render all the data written by my express-app into MongoDB in embedded JavaScript. My goal is to display this data in a simple table that always shows the updat ...

Issue encountered with Bing webmaster API when retrieving keyword statistics: an unknown error occurred resulting in an empty

My goal is to retrieve keyword statistics through the bing webmaster API using JSON GET requests. The required parameters for this operation are as follows: List<KeywordStats> GetKeywordStats( string q, string country, //optional s ...

Utilizing the splice method across multiple instances of a string

When facing a string like "This website is blocked by administrator. Please get the admin permissions. You will be allowed only if permission is granted" that needs to be split into three lines for better readability, one solution is using the splice metho ...

Using $.getJSON is not functioning properly, but including the JSON object directly within the script is effective

I'm currently working on dynamically creating a simple select element where an object's property serves as the option, based on specific constraints. Everything is functioning properly when my JSON data is part of the script. FIDDLE The follow ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...