Access the JSON file within an Ionic promise

Currently, I am working on a project in Ionic and facing an issue while attempting to read a JSON file locally. The process involves using a promise sent from a service which is then injected into a controller. Unfortunately, I keep encountering the error SyntaxError: Unexpected token J, where J always represents the first character of my JSON file.

Does anyone have any insights or solutions for this problem? Any help would be greatly appreciated!

Below is a snippet of my code within app.js:

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
  .state('home', {
     url: '/',
     templateUrl: 'templates/home.html',
     controller: 'MainCtrl as vm',
     resolve: {
        weather: function(MyService) {
           return MyService.getData();
     }
  });

  $urlRouterProvider.otherwise('/');
});

The corresponding code in services.js looks like this:

.factory('MyService', function($http) {

   var base_url = "http://localhost:8100/";

   function getData() {
       return $http.get(base_url+'data/pt_br/mydata.json?callback=JSON_CALLBACK')
          .then(
             function(res) {
                return res;
             },
             function(err) {
                return err;
             }
          )
   }

   return { getData: getData() }
});

Here's how the controller is defined:

.controller('MainCtrl', function(weather) {

   var vm = this;
   vm.weather = weather;
});

Lastly, here is a glimpse of my json file:

JSON_CALLBACK ({
    'Introduction': 'Welcome to my site!',
    'texts' : [
        'text1': 'hello',
        'text2': 'world'
    ]
});

Answer №1

In order to successfully retrieve the data, it is recommended to utilize JSONP. This approach ensures that the function name is included as the initial part of the response.

To implement this change in your code, consider the following:

 return $http.jsonp(base_url+'data/pt_br/mydata.json?callback=JSON_CALLBACK')

For better understanding of JSONP, you can refer to this resource on JSONP. Additionally, a helpful example demonstrating the usage of jsonp can be found in this fiddle.

During network calls, Angular automatically replaces JSON_CALLBACK with its own set value, making it challenging to mock. If you inspect the networking call, you will notice Angular's substitution like so:

angular.callbacks._1({"data": "{\"foo\":\"bar\"}"});

Answer №2

After encountering an issue, I discovered that my json file was mistakenly sent as text-plain. To rectify this, I ran my json file through a json validator tool found at . It became apparent that not only values, but also ALL STRINGS needed to be enclosed in double quotes. Many thanks to @Rajesh for providing the helpful clue.

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

Show an angular variable on my webpage

I am trying to show an Angular variable on an HTML page. In the controller I am using, there is a function like this: $http.get('/api/tasks/?format=json').success(function(data) { $scope.tasks = data; for (var i=0; i < $scope. ...

Explore bar with search button

I'm facing an issue with the code I have for searching on my website. Currently, when a user fills in their search word and presses enter, it executes the command. However, I would like to only run the search script when the user clicks a button inste ...

What is the best way to add a new json line to an existing json file?

I'm currently working on a Python project where I need to manipulate a JSON file. with open('..\config_4099.json', "r") as fid: jaySon = json.load(fid) The json file has a flat structure, so there are no internal elements to modif ...

Converting a string to HTML in Angular 2 with proper formatting

I'm facing a challenge that I have no clue how to tackle. My goal is to create an object similar to this: { text: "hello {param1}", param1: { text:"world", class: "bla" } } The tricky part is that I want to ...

"Comparison: Using jQuery's append() vs native JavaScript's appendChild

Take a look at this example code snippet: function insertText(){ var newText = document.createTextNode(" Inserted text dynamically. "); var paragraph = document.getElementById("p1"); paragraph.appendChild(newText); $("#p1").append("HELLO") ...

How can I combine a nested JSON object into a single object?

When querying a MySQL database in Node.js, I receive the following JSON result: [ [ { val1:1, val2:2, val3:3 } ], [ { val1:1, val2:2, val3:3 } ], [ { val1:1, val2:2, val3 ...

How to parse an array in JSON using Swift 3 and iterate through it

Figuring out how to parse JSON data in Swift 3 has been more challenging than I anticipated, especially coming from a Javascript background. Received response from API: [ { "ID": 1881, "image": "myimageURL", }, { "ID": 6333, "image": "myi ...

Improving the performance of JavaScript execution and enhancing the browser frame rate. The functions setTimeout(..., 0) and setTimeout(..., 1) exhibit distinct behaviors

Exploring the intricacies of browser rendering mechanics and aiming to optimize various action handling on the same event while understanding how it affects repaints. Currently, I am attempting to alter the style of a span element (action 1) and perform a ...

What is the best way to input JSON objects into an autocomplete feature?

When I tried to implement an autocomplete feature using jQuery and Ajax, I encountered an issue. While the objects were successfully requested and appeared in the preview tab under "network," I struggled with rendering them into the HTML... $(document).r ...

What is the best way to dynamically display components in React Native based on changing values returned from an API call?

In my React Native app, I am integrating API calls from D&D 5E API. One feature I am working on is displaying detailed information about a selected monster when the user makes a choice. However, I'm struggling to determine the best approach for creati ...

Separating Angular JS controller and Factory into individual files allows for easier organization and

As someone new to web development and Angular, I recently created a module, factory, and controller all in the same file (app.js). Below is an example of the code: //Main Module var ipCharts = angular.module('ipCharts', []); //Factory ipCharts. ...

Obtain the values from controls within the <td> element

I'm experiencing some difficulty creating an array of table cell values because the cells contain controls, not just plain text. $("#tbl_CGT tr").each(function() { var arrayOfThisRow = []; var tableData = $(this).find('td'); if (tab ...

Error encountered due to circular structure in the data being posted in the

const formulaData = $(htmlContainer).find("ins").map(function (i, el) { return { fName: $(el).attr("data-record-name"), fID: $(el).attr("data-record-id"), fContent: $(el).text() } }); //keep if (for ...

Increase the date by one day excluding weekends (Saturday and Sunday)

My current code is designed to add +1 day to the current date. var date = '30 Apr 2010'; var actual_date = new Date(date); var final_date = new Date(actual_date.getFullYear(), actual_date.getMonth(), actual_date.getDate()+1); Now, I am looking ...

How to implement datepicker on multiple input fields

Below are the two input fields that have datepicker functionality: <div class="row"> <input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min="minDate" max="'2015-06-22&apos ...

CSS import is causing issues with the pagination in React JS

I recently started using react js pagination from https://www.npmjs.com/package/react-js-pagination. However, I encountered an issue with the CSS import. The error message I received was: Module not found: Can't resolve 'bootstrap/less/bootstrap. ...

Is it possible to alter objects through the use of jQuery.map?

I'm working with a key-value pair that looks like this: var classes = { red: 'Red', green: 'Green' }; Is there a way to add a specific value before each key in the pair? Can jQuery.map help with this task? The desired end result ...

What is the best way to connect specific nodes to the edge of a canvas in cytoscape and create perfectly straight lines?

In the center column of my article, I have two graphs created with cytoscape showing "ancestors" and "descendants" on the sides. I am interested in displaying the connections ("edges") from the articles in the final generation of "ancestors" to the articl ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

AngularJS requires that JSON object property values be converted to strings in order to be displayed as actual templates

Each tab click accesses a json array containing unique templates such as ui-grid or c3 chart directive (c3.js). When a specific tab is clicked, the template in string format must be rendered into actual templates like ui-grid, c3-chart, etc. var sampleJs ...