In a Django/React app I am building, I use an API call to get some ids, which returns an object like this:
{
"0": {
"0": "7y8X0Z04gJCKtfrnSAMywJ",
"1": "781V2Y5LPtcpgONEOadadE"
},
"1": {
"0": "7nCONy10IHp7XD3oYZ0lcx"
}
...
}
I want to then use JSON.stringify()
to send it in another API request, but when I log it in console it looks like this:
{"0":{},"1":{}, ...
If I create a mock object of the same structure and stringify it, it works as expected (logged in console and confirmed by sending to my API:
testObj stringify {"0":{"0":"7y8X0Z04gJCKtfrnSAMywJ","1":"781V2Y5LPtcpgONEOadadE"},"1":{"0":"7nCONy10IHp7XD3oYZ0lcx"}}
also, if I save my object locally in console, then stringify it, it works: console.log screenshot
If I can log the object properly, and stringify in console, why won't it work in the below code? allTopTracksObj is my object
function addItemsToPlaylist(allTopTracksObj, playlistId) {
const encodedPlaylistId = encodeURIComponent(playlistId);
const testObj = {
0: { 0: '7y8X0Z04gJCKtfrnSAMywJ', 1: '781V2Y5LPtcpgONEOadadE' },
1: { 0: '7nCONy10IHp7XD3oYZ0lcx', }
}
console.log('testObj', testObj)
console.log('allTopTracksObj', allTopTracksObj)
console.log('testObj stringify', JSON.stringify(testObj))
console.log('allTopTracksObj stringify', JSON.stringify(allTopTracksObj))
fetch(`/spotify/add-items-to-playlist/?playlistId=${encodedPlaylistId}`,
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(allTopTracksObj)
})
.then(function (res) {
console.log('addItemsToPlaylist result', res) })
.catch(function (res) { console.log(res) })
}
This function is called after ensuring the object is fully generated with an async/await call:
await createTopNTracksArray(artistIdArray).then((obj) => {
if (Object.keys(obj).length > 0 && playlistId.length > 0) {
addItemsToPlaylist(obj, playlistId);
}
I also read some answers that hinted that the objects may not be enumerable (if I built them incorrectly), but checking in console confirms it is
Appreciate any help, thanks.