Skip to content

Instantly share code, notes, and snippets.

@laurenancona
Created March 22, 2017 15:28
Show Gist options
  • Save laurenancona/bd560948d71054e3d1477e43c4d48cb6 to your computer and use it in GitHub Desktop.
Save laurenancona/bd560948d71054e3d1477e43c4d48cb6 to your computer and use it in GitHub Desktop.
Access local JSON data with Javascript
[{
"name": "Harry",
"age": "32"
}]

What

An updated guide/collection of guides on how to access JSON data with JavaScript

Original Question on Stack Exchange.


Example 1

For reading the external Local JSON file (data.json) using java script

data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';

// Mention the path of the json file in the script source along with the javascript file.

<script type="text/javascript" src="data.json></script>
<script type="text/javascript" src="javascrip.js"></script>

2.Get the Object from the json file

var mydata = JSON.parse(data);
 alert(mydata[0].name);
 alert(mydata[0].age);
 alert(mydata[1].name);
 alert(mydata[1].age);

http://www.askyb.com/javascript/load-json-file-locally-by-js-without-jquery/


Example 2

Depending on your browser, you may access to your local files. But this may not work for all the users of your app.

To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Once your file is loaded, you can retrieve the data using:

var jsonData = JSON.parse(theTextContentOfMyFile);
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'file.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// .open will NOT return a value but simply returns undefined in async mode so use a callback
callback(xobj.responseText);
}
}
xobj.send(null);
}
// Call to function with anonymous callback
loadJSON(function(response) {
// Do Something with the response e.g.
//jsonresponse = JSON.parse(response);
// Assuming json data is wrapped in square brackets as Drew suggests
//console.log(jsonresponse[0].name);
});
@bohnmedia
Copy link

The quotes behind "data.json" are missing in Example 1.

@shivam-bisht
Copy link

Access to XMLHttpRequest at 'file:///home/monk/Projects/rbtech/alKarera/ecoBowlers2015.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

@McGreg000
Copy link

Access to XMLHttpRequest at 'file:///home/monk/Projects/rbtech/alKarera/ecoBowlers2015.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Is the browser's protection. You can´t use for acces to local files. If you want to try you can install one webserver in your machine for local projects.

@webb24h
Copy link

webb24h commented Jan 2, 2021

Example 1 does not work :/

Yes because it's wrong. It's not a json file. It's a hardcoded javascript array and should be put inside a javascript file. You cannot put quotes in a json file. It doesn't pass validation. It will never run.

This solution works

data.js

data = [{
    "Employees": {

        "name": "John",
        "age": 30,
        "cars": ["Ford", "BMW", "Fiat"],

        "name": "Jane",
        "age": 34,
        "cars": ["Ford", "BMW", "Fiat"],

        "name": "Grogu",
        "age": 50,
        "cars": ["Ford", "BMW", "Fiat"]

    }
}];

second.js
console.log(data[0].employees);

index.html

<script ttype="text/javascript" src="data.js"></script>
<script ttype="text/javascript" src="second.js"></script>

@sujantkumarkv
Copy link

sujantkumarkv commented Apr 1, 2022

Example 1 does not work :/

Yes because it's wrong. It's not a json file. It's a hardcoded javascript array and should be put inside a javascript file. You cannot put quotes in a json file. It doesn't pass validation. It will never run.

This solution works

data.js

data = [{
    "Employees": {

        "name": "John",
        "age": 30,
        "cars": ["Ford", "BMW", "Fiat"],

        "name": "Jane",
        "age": 34,
        "cars": ["Ford", "BMW", "Fiat"],

        "name": "Grogu",
        "age": 50,
        "cars": ["Ford", "BMW", "Fiat"]

    }
}];

second.js console.log(data[0].employees);

index.html

<script ttype="text/javascript" src="data.js"></script>
<script ttype="text/javascript" src="second.js"></script>

Hey it's urgent, I'm stuck on this.
If I'm seeing it correct, data.js & second.js are different files.
I have a json file in my directory, I want to load that into a js file and work with it. How do I achieve that. I did fs.readFile(...) but that returns null

Your help is realllly appreciated. Thanks :)

@webb24h
Copy link

webb24h commented Apr 1, 2022

Example 1 does not work :/

Yes because it's wrong. It's not a json file. It's a hardcoded javascript array and should be put inside a javascript file. You cannot put quotes in a json file. It doesn't pass validation. It will never run.
This solution works
data.js

data = [{
    "Employees": {

        "name": "John",
        "age": 30,
        "cars": ["Ford", "BMW", "Fiat"],

        "name": "Jane",
        "age": 34,
        "cars": ["Ford", "BMW", "Fiat"],

        "name": "Grogu",
        "age": 50,
        "cars": ["Ford", "BMW", "Fiat"]

    }
}];

second.js console.log(data[0].employees);
index.html

<script ttype="text/javascript" src="data.js"></script>
<script ttype="text/javascript" src="second.js"></script>

Hey it's urgent, I'm stuck on this. If I'm seeing it correct, data.js & second.js are different files. I have a json file in my directory, I want to load that into a js file and work with it. How do I achieve that. I did fs.readFile(...) but that returns null

Your help is realllly appreciated. Thanks :)

There are several ways you can fetch data from a JSON file. One easy way with ajax :

$.ajax({
    type: "Get",
    url: "data.json",
    dataType: "json",
    success: function(data) {

     console.log(data);

    },
    error: function(){
        alert("json not found");
    }
});

@Fayaz-khani
Copy link

The quotes behind "data.json" are missing in Example 1.

we can put double quotes easily there in json file dear

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment