0

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

KtheVeg
  • 133
  • 1
  • 7
  • 1
    "Unexpected token o" almost _always_ means you're not getting JSON at all: open your dev tools, select the network tab, rerun your fetch and look at what you're _actually_ getting back. – Mike 'Pomax' Kamermans Nov 05 '20 at 20:51
  • "Unexpected token o" typically arises when you attempt to parse something that has already been parsed. Log `typeof data` and if it's "object", jQuery has already parsed it for you. – Heretic Monkey Nov 05 '20 at 21:07

2 Answers2

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.

Justin Rice
  • 1,111
  • 12
  • 13
  • I think you are correct because I see the same error when I try this example: var e = JSON.parse({thing:"test"}) That example parse an object but it gives an error, because it should be parsing the JSON string. – raddevus Nov 05 '20 at 20:58
  • In other words, can just do : AnnouncementsJSON = data; – raddevus Nov 05 '20 at 21:03
  • @raddevus you're correct! JSON.parse expects a stringified object so it can turn it into an object. Counter to that is JSON.stringify which takes an object and turns it into a string. It is very useful for storing encrypted objects in local storage. – Justin Rice Nov 09 '20 at 21:03
-1

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...