Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Alexander Hovde
Alexander Hovde
4,118 Points

Loading a local .json file with javascript

I think you can load a local .json file with basic javascript (please correct me if I am wrong), but I can't seem to figure out how to do it...

Here are my code snippets.

test.json:

{ "name": "Molecule Man", "age": 29, "secretIdentity": "Dan Jukes", "powers": [ "Radiation resistance", "Turning tiny", "Radiation blast" }

test.js:

var test = $.getJSON(test.json); var jsontest = JSON.parse(test);
console.log(jsontest);

Thanks!!!

Nik Myers
Nik Myers
5,744 Points

Your snippet involves jQuery, so it's not plain JavaScript, and you're passing getJSON a non-existent variable (or rather, an undefined property of the test object) instead of a string (or valid variable) pointing to the .json file.

Also, if you mean "local" in the context of opening an .html page via the file:// protocol, browsers don't typically let you perform ajax operations in that case and you should be using an http server (either locally or remotely, whatever floats your boat).

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

Are you trying to do it with plan javascript or using the jquery $.getJSON

Alexander Hovde
Alexander Hovde
4,118 Points

Thanks Dave. I am just trying to access a .json file in my .js file however I can. It does not need to be plain javascript.

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

One good place to start is reading the jquery doc link $.getJSON and follow that up with the MDN Working with JSON

If you have a local *amp stack dev environment, here's some code to get started (basically from the jquery doc example)

HTML - index.html - you'll need to download jquery or change the reference to use the CDN

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON Tester</title>
</head>
<body>
<h1>JSON Tester</h1>
<script src="jquery-3.3.1.min.js"></script>
<script src="test.js"></script>
</body>
</html>

Javascript - test.js

$.getJSON( "test.json", function( json ) {
    console.log( "JSON Data received, name is " + json.name);
});

JSON - test.json - place in document root, with above two files - or need to resolve the path

{ "name": "Molecule Man",
    "age": 29,
    "secretIdentity": "Dan Jukes",
    "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
  }