d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Is It Possible To Set A Javascript Variable To > A .json File In The Same Directory?
Add Reply New Topic New Poll
Member
Posts: 9,525
Joined: Nov 5 2005
Gold: 1,338.00
Jan 28 2015 11:15am
In other words, say I have an index.html file.

In that index.html file, I have a <script> section that does stuff.

In the same directory as index.html, I have someStuff.json (which is a JSON file).

In that script section, I want to do something like this:

<script>

...
var newVariable = someStuff.json;
...

</script>

and now that newVariable contains unparsed JSON, where I can there on do stuff like

var otherNewVariable = JSON.parse(newVariable);

Does that make sense?
Member
Posts: 18
Joined: Jan 6 2015
Gold: Locked
Trader: Scammer
Jan 28 2015 02:51pm
You can do something like this:

Code

function readJSON(file) {
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
if (request.status == 200)
return request.responseText;
};

var myObject = JSON.parse(readJSON('/local/path/to/json'));
Member
Posts: 9,525
Joined: Nov 5 2005
Gold: 1,338.00
Jan 29 2015 12:46pm
Quote (MisterTrain @ Jan 28 2015 02:51pm)
You can do something like this:

Code
function readJSON(file) {
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
if (request.status == 200)
return request.responseText;
};

var myObject = JSON.parse(readJSON('/local/path/to/json'));


Oh, that looks viable.

so if my file's name was employees.json, then it would be:

JSON.parse(readJSON('employees.json'));?

I'm trying it out and it's being weird.

EDIT: got it, was missing a bracket in my json file.

THANKS!

This post was edited by Rejection on Jan 29 2015 01:02pm
Member
Posts: 18
Joined: Jan 6 2015
Gold: Locked
Trader: Scammer
Jan 30 2015 07:44am
Quote (Rejection @ Jan 29 2015 12:46pm)
Oh, that looks viable.

so if my file's name was employees.json, then it would be:

JSON.parse(readJSON('employees.json'));?

I'm trying it out and it's being weird.

EDIT: got it, was missing a bracket in my json file.

THANKS!


if it is in the same directory, yes just 'employees.json'

No problem, glad I could help!
Member
Posts: 11,610
Joined: Oct 28 2008
Gold: 1,795.00
Feb 1 2015 09:54am
ajax equivalent which is nice for async calls:

Code

$.ajax({
url: '/employees.json',
type: "GET",
dataType: "json",
success: function (data) {
alert(data.responseText);
}
});
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll