I have a really simple JSON data file with no kind of wrapping, e.g.:
[{"name:","fakename"}, {"lang:", "javascript"}]
I'm trying to use this data in a js script in the same directory. I'm reading in both files in the document <head>
, like such:
<script id="myJSON" src="data.json"></script>
<script src="myScript.js"></script>
and then the part I'm stuck on is how to get myScript to SEE that JSON data. In the script I can do:
d = document.getElementById("myJSON");
console.log(d);
The script returns the DOM element "myJSON" but I don't know how to access its JSON contents. I figured it would be a property like 'text' or 'value' or 'innerHTML' but I don't see it anywhere. I've tried various combinations of the type attribute in the tag but none of that makes any difference.
I know I could use an API like fetch but that's more complexity than I want. My best idea so far is to edit the json file to put an identifier at the beginning of the json file, like var myJSON = '[{"json"}]';
so then myScript would have a clear handle to JSON.parse(myJSON)
. But that's an extra step in an automated process which I don't want (or think I need).
How do I get my JS to see this "anonymous" JSON?
CodePudding user response:
If you don't want to use fetch, you could use the server side code (PHP, ASP, etc) to write the text of the JSON into a hidden div in the page, and then you could use getElementByID
to get the text, followed by parse
to get an object that represents the JSON data.
CodePudding user response:
This was not that much extra code but it was kind of a pain to wrap my head around. I had to wrap everything in a .then
clause of fetch, or of an async function which called fetch. Here's what my code ended up looking like.
readJSONFile().then(jq => {
for (i = 0; i < jq.length; i) {
console.log( jq[i].myJSONKey )
});
async function readJSONFile() {
const response = await fetch('data.json');
const jq = await response.json();
return jq;
}