I’m trying to fetch a JSON data from our server and then inserting it in a <script>
TAG in client-side. See below:
JavaScript
x
24
24
1
<script>
2
const bodyTag = document.getElementsByTagName("body")[0];
3
4
const url = "https://ourAPI.com";
5
const parameters = {
6
method: "GET",
7
headers: new Headers(),
8
mode: "cors",
9
cache: "default",
10
};
11
12
fetch(url, parameters).then((response) => {
13
if (response.ok) {
14
response.json().then((data) => {
15
console.log(data.imports); //It shows me data fetched.
16
const importmap = document.createElement("script");
17
importmap.type = "systemjs-importmap";
18
importmap.innerHTML = data.imports; //It shows me "[object Object]".
19
bodyTag.appendChild(importmap);
20
});
21
}
22
});
23
</script>
24
The problem is: when I console.log(data.imports)
, it shows me the fetched data, but the <script>
TAG looks like this:
JavaScript
1
2
1
<script type="systemjs-importmap">[object Object]</script>
2
What it looks strange for me is when I use JSON.stringify(data)
, it is possible to see that the data was extracted from the API as expected (see below), but in JSON format it doesn’t extract anything…
JavaScript
1
2
1
<script type="systemjs-importmap"> all data in string format </script>
2
Could anyone tell me where I’m doing wrong?
Advertisement
Answer
Anything you assign to innerHTML
will be implicitly converted to a string. Hence, the [object Object]
you’re seeing. In order to see the actual JSON value, you can explicitly convert this object to a JSON-string:
JavaScript
1
2
1
importmap.innerHTML = JSON.stringify(data.imports);
2