Zed Zed - 1 year ago 120
Javascript Question

getJSON object not appearing in console.log

I am a beginner testing getJSON in a simple front-end project. I've learned that I can't use the file:// URL prefix that I've been using previously, and must simulate a server (is this correct?). I've utilized Python's built-in server functionality by typing in python3 -m http.server 8000 into the terminal (OS X) from my project directory.

I can now type into my browser and it will load my index.html. I have two other files: app.js and aceOfSpades.json, which are located in a folder called javascripts, which sits at the same level as index.html.

When index.html is loaded, the only value displayed in the console is "hello world". This tells me that app.js is being correctly loaded, but the getJSON function is either (1) not seeing the aceOfSpades.json file, (2) is seeing the file but not placing its object into the "card" parameter, or (3) is possibly getting caught up in my Python built-in server. Perhaps it's something else entirely.

When I look in the "sources" tab of the Chrome developer panel, the only file listed in the javascripts folder is app.js. aceOfSpades.json is nowhere to be found!

My question: why isn't my JSON object being printed to the console given the following code? How can I solve this? Thank you.


<!doctype html>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="javascripts/app.js"></script>


var main = function () {
"use strict";

$.getJSON("/javascripts/aceOfSpades.json", function (card) {
console.log("your card should appear after this");

console.log("hello world");



rank: "ace",
suit: "spades"

Answer Source

It is probably because your properties aren't surrounded by quotes, resulting in invalid JSON.

    "rank": "ace",
    "suit": "spades"

From jQuery Docs (emphasis added):

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download