Issue encountered while parsing JSON file using AngularJS

Having some trouble reading a json file in AngularJS using $http.get and encountering errors in the browser console.

Check out my Plunker example: http://plnkr.co/edit/SDRpu1MmrTPpgpdb6Kyk?p=preview

Below is the code snippet:

Javascript:-

var jayApp = angular.module('jayApp', []);

jayApp.controller('jayController', function($scope, $http){

  $scope.entities = {};

    $http.get("test.json").success(
        function(data, status, headers, config) {
            $scope.entities = data;
        }
    );
})

HTML

    <!DOCTYPE html>
<html>

  <head>
    <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1838e8e959295938091a1d2cfd2cfd4">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
    <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7c5c8c8d3d4d3d5c6d7e79489948992">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cosmo/bootstrap.min.css" />
    <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d3dedec5c2c5c3d0c1f1829f829f84">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e48e959181969da4d5cad5d5cad7">[email protected]</a>" data-semver="1.11.3" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d1dcdcc7c0c7c1d2c3f3809d809d86">[email protected]</a>" data-semver="3.3.5" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9a959c8e979a89d59188bbcad5cfd5cc">[email protected]</a>" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>

    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app='jayApp' ng-controller='jayController'>
    <h1>Read Json from file </h1>

    Data : {{entities}}
  </body>

</html>

Update:

Error

SyntaxError: Unexpected token '
    at Object.parse (native)
    at fromJson (https://code.angularjs.org/1.4.7/angular.js:1252:14)
    at defaultHttpResponseTransform (https://code.angularjs.org/1.4.7/angular.js:9414:16)
    at https://code.angularjs.org/1.4.7/angular.js:9505:12
    at forEach (https://code.angularjs.org/1.4.7/angular.js:336:20)
    at transformData (https://code.angularjs.org/1.4.7/angular.js:9504:3)
    at transformResponse (https://code.angularjs.org/1.4.7/angular.js:10276:23)
    at processQueue (https://code.angularjs.org/1.4.7/angular.js:14745:28)
    at https://code.angularjs.org/1.4.7/angular.js:14761:27
    at Scope.$eval (https://code.angularjs.org/1.4.7/angular.js:15989:28)(anonymous function) @ angular.js:12477(anonymous function) @ angular.js:9246processQueue @ angular.js:14753(anonymous function) @ angular.js:14761Scope.$eval @ angular.js:15989Scope.$digest @ angular.js:15800Scope.$apply @ angular.js:16097done @ angular.js:10546completeRequest @ angular.js:10744requestLoaded @ angular.js:10685

Answer №1

There were a couple of issues with your plunker. Firstly, there was an error due to the incorrect path to the JSON file, resulting in a 404 error. By removing the leading /, this issue was resolved.

The main problem lies in the invalid format of your JSON.

It should appear as:

{
  "name": "Alice",
  "city": "London"
}

You originally used single quotes (') instead of the required double quotes (").

Answer №2

There seems to be an issue with the JSON file path, make sure you remove any unnecessary '/' in the file path.

JSON Data:

{
  "name":"Alice",
  "city":"New York"
}

JavaScript Code:

$http.get("example.json").then(
    function(response) {
      console.log(response.data);
        $scope.items = response.data;
    }
);

Check out the revised Plunker for more details.

Answer №3

Error in JSON format... The correct format should be:

{
  "firstName":"Alice",
  "lastName":"Smith"
}

In addition, on your Plunk, the URL for the call is incorrect (remove the / before data.json).

$http.get("data.json").then( ...

Answer №4

  1. Upon reviewing your JSON file, it appears that there are syntax errors present which is the primary issue causing the interpreter to not be able to read the JSON data. A. I have rectified this by adding double quotes to your **keys** and B. enclosing all your JSON objects within curly brackets {}

  2. It is important to note that you cannot parse a file that is already a JSON object; parsing is done when the data is stringified. Therefore, I have removed the 'parse' word and adjusted the code as follows:

    $http.get("test.json").success(
        function(data, status, headers, config) {
            $scope.entities =data;  
        }
    );
    

Check out the fixed plunker example here: http://plnkr.co/edit/G5Y62tQuJit3ZvjHbKQ8?p=preview

I did not add double quotes to all your keys as there were too many, but this adjustment should help you understand where the mistake was made. https://i.sstatic.net/p8Fd0.png I hope this helps and good luck with your project.

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

Ways to initiate the download of an audio link using JS without the need for the browser to redirect to a different page

I am looking to create a script that can automatically download audio files from a website. The problem I'm encountering is that using element.click() to simulate a "click" event doesn't work as expected, as the browser ends up navigating to the ...

Troubleshooting the issue: React Native Redux not navigating correctly using API IDs

Lately, I've been utilizing Redux for my application and it's been going well. However, I recently encountered a roadblock that has halted my coding progress temporarily. My current challenge involves creating a navigation system using the ID of ...

Swift - Transforming an NSMutableArray into an array of MKAnotationViews

Currently, I have an array of BarAnnotation objects like this: var bars = [BarAnnotation(latitude: 42.022352, longitude: -93.650413, name: "Micky's Irish Pub", deal: "$2 Drinks 9PM-1AM"), BarAnnotation(latitude: 42.021948, longitude: -93.650348, ...

What is the process for retrieving my dates from local storage and displaying them without the time?

Having an event form, I collect information and store it in local storage without using an API. However, I face a challenge when extracting the startdate and enddate out of localstorage and formatting them as dd-mm-yyyy instead of yyyy-mm-ddT00:00:00.000Z. ...

Creating a series of promises in a structured chain

How can the code structure be improved, especially regarding exception handling within a "promise chain"? $("#save").click(function(e) { e.preventDefault(); let $self = $(this); let profile = {} $self.prop("disabled" ...

Unable to convert the String prop that was passed from the parent component to a JSON object using JSON.parse() in a React child component

Issue Overview: The SLTree React component retrieves a JSON object using Ajax, converts it to a string, and then passes it as a property to two other components - Editor and TNode. While the Editor component (which contains CodeMirror) functions correct ...

The MVC6 controller is receiving null values for the posted data

I'm currently in the process of migrating my web application from MVC5 to MVC6. While this function worked smoothly in MVC5, it's experiencing issues in MVC6. When I use AngularJS to post data to this WebAPI method, the search parameter always c ...

Generating an array within the custom hook results in the value being re-rendered with each change in state

While working on a custom hook in react native, I ran into an issue with the combination of useEffect and useState that led to an infinite loop. To demonstrate the problem, I created a small snack: import React, { useEffect, useState, useMemo } from &apos ...

Storing prop object in LocalStorage when clicking on a Vue3 component

I am currently attempting to pass a prop (faction) from a Component called Faction Option when the @click event for the option occurs. FactionOption.vue <script setup> import { selectFaction } from '../../composables/selectFaction'; def ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

Trouble encountered while trying to utilize a Promise to define a global variable

I am attempting to populate a global variable using a function and then call subsequent functions after the data is retrieved. Below is the current code I have: $(function () { var jsonData = {}; var dataRetrievalPromise = function () { r ...

Bootstrap allows for the use of video backgrounds, offering the option for borders to be included

Having trouble with a Bootstrap HTML page featuring a video background? The issue is that sometimes the video has borders on the left and right, and occasionally on mobile devices as well. Oddly enough, when the browser (Chrome or Firefox) is refreshed, th ...

Manipulate audio files by utilizing the web audio API and wavesurfer.js to cut and paste audio

I am currently working on developing a web-based editor that allows users to customize basic settings for their audio files. To achieve this, I have integrated wavesurfer.js as a plugin due to its efficient and cross-browser waveform solution. After prior ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

Searching for curly braces in Python using regular expressions

As I work through a JSON file, I am utilizing regex to extract information regarding company financial KPIs and their corresponding values. For instance, the regex for "grossProfits":{"raw":19805000000,"fmt":"19.8B","longFmt":"19,805,000,000"} would cap ...

Looping through JSON keys using ng-repeat in AngularJS

I am currently working on a project where I need to populate some JSON data retrieved from the Google Tag Manager API and then send this information to the frontend which is developed in AngularJS. At the moment, I am utilizing ng-repeat on a card compone ...

What is the best way to convert string dot notation into a nested object structure?

Is there a way to convert a dot notation string such as 'a.b.c.d' into an Object? And if the Object referenced doesn't exist, can we automatically create an empty one? var str = 'a.b.c.d' var obj = {} // Now what? function dotTo ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

Implementing CSS styles with the className attribute in a Material UI component within a ReactJS application sourced from a dynamic JSON object

I have a dynamic JSON object that includes a button element. I am using createElement and Material UI to display the data from this object. I wanted to add custom CSS styling to the button component using className, but I've been struggling to achiev ...

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...