quentinkrammer
quentinkrammer

Reputation: 62

Importing Data fom JSON-File into JavaScript

The "console-log(states)" line in he HTML File returns an "undefined". Does anyone know why? My goal here is to store the data from the JSON-File in a JavaScript-Variable. The result should be a list that contains 3 dictionaries.

Both files are in the same directory.

Thanks a lot for any help!

HTML-File

<html>
<head>
<script type="text/javascript" src="states_Ex1.json"></script>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>

<script> var states=states_Ex1.json</script>
<script>
console.log(states) // --> undefined
</script>

</body>
</html>

JSON-File

[
    {
        "gene1": true,
        "gene2": true,
        "nextStateIndex": 1
    },
    {
        "gene1": true,
        "gene2": false,
        "nextStateIndex": 2
    },
    {
        "gene1": true,
        "gene2": true,
        "nextStateIndex": 1
    }
]

Upvotes: 0

Views: 47

Answers (1)

Alex Douglas
Alex Douglas

Reputation: 221

New Answer

I've found a series of answers here for accessing local JSON files.

I tried @seppoo0010's method and it works on my end. Give it a shot:

$.getJSON("your-path-to-file.json", function(states) {
    console.log(states); // this will show the info it in firebug console
});

You'll need to parse the JSON. Try this: ... var states = JSON.parse(states_Ex1.json) ...

Upvotes: 1

Related Questions