Although it's not valid JSON, I've found that by declaring this as a variable directly in my code, I can treat it like an object.
<script>
// this will result in object
var mydata = {
users: [{
person: {
firstName: "Garry",
lastName: "Finch"
},
jobTitle: "Front End Technical Lead",
twitter: "gazraa"
}, {
person: {
firstName: "Hans",
lastName: "Wurst"
},
jobTitle: "Photographer",
twitter: "photobasics"
}, {
person: {
firstName: "Paul",
lastName: "Stark"
},
jobTitle: "LEGO Geek",
twitter: "minifigures"
}]
};
console.log('mydata: ' + mydata);
console.log(mydata);
</script>
https://i.sstatic.net/II7ef.png
Now, I want to save the same information into a file called "table.data.js". The contents of the file would look like this:
//BEGIN
{
users: [{
person: {
firstName: "Garry",
lastName: "Finch"
},
jobTitle: "Front End Technical Lead",
twitter: "gazraa"
}, {
person: {
firstName: "Hans",
lastName: "Wurst"
},
jobTitle: "Photographer",
twitter: "photobasics"
}, {
person: {
firstName: "Paul",
lastName: "Stark"
},
jobTitle: "LEGO Geek",
twitter: "minifigures"
}]
}
//END
I then attempted various methods to read this file
$.ajax({
contentType: "application/json; charset=utf-8",
url: "Content/modules/Controls/table/table.data.js",
data: "{}",
dataType: "json",
success: function(data) {
var json = data;
console.log(json);
}
});
I also tried using $.get and $.getScript. However, the result was never the same object.
//var jqxhr = $.get("Content/modules/Controls/table/table.data.js", function () {
var jqxhr = $.getScript("Content/modules/Controls/table/table.data.js", function (data, textStatus, jqxhr) {
console.log("success");
}).done(function (data) {
console.log(data);
testdata = JSON.stringify(data);
console.log(testdata);
}).fail(function () {
console.log("error");
}).always(function () {
console.log("finished");
});
The result always ended up being plain text in the console. It seems like a simple task for some, but it's quite challenging for me.
EDIT: Thank you to everyone who responded. In conclusion, it seems that it's not possible to load external data, store it in a variable like "mydata", and have it behave the same way as when declared directly in the code. I'll convert the data to valid JSON instead.
If I were to give a medal for the shortest and most precise answer, it would go to @Quentin. But, thank you all for your insights.