I have some code below to transform a fetched json into string and remove the braces and parse it into a map variable:
let result = '';
let map = [];
fetch(link)
.then(function(response) {
return response.json();
}).then(function(json) {
result = JSON.stringify(json); //json here is like [{'a':1,'a2':2},{'b':11,'b2':12}]
result = result.substring(1, result.length - 1);
map = JSON.parse(result);
}).catch(function(ex) {
console.log('parsing failed', ex);
});
I've tried to simply set map=json
but it both gives out the same error that I have duplicate keys for the map.
If I hard code my map
variable to lets say [{'id':1,code: 007},{'id':2, code:014}]
it works. I've tried to log result
after changing it to a string and its exactly as the example. So in other words, setting map=json
should work in the first place.
I think I might be missing something. What is it?
EDIT #1:
fetch(link)
.then(function(response) {
return response.json();
}).then(function(json) {
setData(json);
document.getElementById("result").innerHTML = json;
}).catch(function(ex) {
console.log('parsing failed', ex);
});
function setData(json) {
map = json;
}
I've tried the solution given by Naomik except without the response ok
part.
I'm still receiving the same error as map = json
. Any help with this?