'JSON object not formatting properly
I have some code that fetches data from an API and writes it to a file, the API returns tokenIdMetadata that has a bunch of information in it that I do not want so I made it into a new JSON object tokenMetadata and save that to a file as seen below.
const tokenIdMetadata = await Moralis.Web3API.token.getTokenIdMetadata(options);
const tokenMetadata = {};
tokenMetadata.token_id = tokenIdMetadata.token_id;
tokenMetadata.metadata = tokenIdMetadata.metadata;
fs.writeFileSync(folderName.concat('/', collectionSlug, '_', tokenID, '.json'), JSON.stringify(tokenMetadata, null, 4));
The problem is the code returns a string in the JSON file that is not formatted properly
"token_id": "4",
"metadata": "{\"name\":\"Arcade Land Mega #4\",\"image\":\"ipfs://QmaJyxmwWkH17P7cpzRDFqcQwh7HYZ53VS9pJN3rtWKVPh\",\"description\":\"Arcade Lands are digital properties in an interoperable metaverse that serves as your web3 home for all your NFTs. Land owners will get additional benefits within the Arcadeverse.\",\"attributes\":[{\"trait_type\":\"Size\",\"value\":\"Mega\"},{\"trait_type\":\"Area\",\"value\":\"Frozen\"},{\"trait_type\":\"Underground\",\"value\":\"Weird Rocks\"}]}"
This is how it should be formatted
"token_id" : "4",
"metadata" : {
name: 'Arcade Land Mega #4',
image: 'ipfs://QmXYYbVEFqVPRELzPN3fgCw9v3wr2iQqixbVaGS1JTH6mS',
description: 'Arcade Lands are digital properties in an interoperable metaverse that serves as your web3 home for all your NFTs. Land owners will get additional benefits within the Arcadeverse.',
attributes: [
{ trait_type: 'Size', value: 'Mega' },
{ trait_type: 'Area', value: 'Frozen' },
{ trait_type: 'Underground', value: 'Weird Rocks' }
]
}
I was wondering how I would go about fixing this.
Solution 1:[1]
I have checked example result of this API call in the documentation https://docs.moralis.io/moralis-dapp/web3-api/token#gettokenidmetadata . It looks like this is about failing to decode incoming JSON.
I think replacing tokenIdMetadata.metadata by JSON.parse(tokenIdMetadata.metadata) should fix that.
The final code should look like the following:
const tokenIdMetadata = await Moralis.Web3API.token.getTokenIdMetadata(options);
const tokenMetadata = {};
tokenMetadata.token_id = tokenIdMetadata.token_id;
tokenMetadata.metadata = JSON.parse(tokenIdMetadata.metadata);
fs.writeFileSync(folderName.concat('/', collectionSlug, '_', tokenID, '.json'), JSON.stringify(tokenMetadata, null, 4));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
