skip to Main Content

I’m trying to get Data from a server and parse it so I can format it into something to display in HTML

I’m getting issues with Parsing the data from the JSON file

Here’s my code:

JS

    var AnnouncementsJSON
    $.get("data/announcements.json", function(data) {
        console.log(data)
        AnnouncementsJSON = $.parseJSON(data)
    });
    console.log(AnnouncementsJSON)

announcements.json


    {
    "announcements":[
        {
            "title":"This is the Announcement!",
            "subtitle":"This is going to be used as announcements",
            "link":"/somewhere.html"
        }
    ]
}

Console/Inspect Element:

(index):189 {announcements: Array(1)}
VM976:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at Function.parse [as parseJSON] (<anonymous>)
    at Object.success ((index):190)
    at c (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at l (jquery.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2)
(anonymous) @ (index):190
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
l @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
load (async)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
S.<computed> @ jquery.min.js:2
(anonymous) @ (index):188

Above the Error message, it shows {Announcements: Array(1)}, so I know I can access the JSON file from the browser. Plus I navigated to it and I was able to access it

2

Answers


  1. I believe the solution you are looking for is JSON.parse, but I also see this payload as not needing JSON.parse because it comes in as an object. $.get returns an object with the response payload.

    Login or Signup to reply.
  2. You should be able to access it without any additional parsing. I think you are getting that error because you are trying to parse already parsed json…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search