Syntax error with Truffle

Hey guys
I was having issues with getting a response to my cloud function and was told to install truffle again and start another ganache and Moralis server. Now Iā€™m getting this error and Iā€™m confused at how this has happened and how to fix it.
Cheers

Try restarting VSCode and close any existing terminals.

Hey
Iā€™ve tried reinstalling everything. Iā€™ve tried renaming files. Iā€™ve tried closing all terminals and restarting VS code and I downloaded a new npm. Iā€™m very lost with this issue.
Cheers

For that error, have a look at this thread which may help.

Hey Glad
This might be a newbie thing but Iā€™m getting a error for the it says expected a JSON object, array or literal. Iā€™ve tried a few other ways of writing the DOCTYPE and havenā€™t got far. Do you know what would fix this?
Cheers

Like 1 should be <!DOCTYPE html>

Hi Qudusayo
Thanks for the quick reply.
Iā€™ve just tried that and nothing has changed. Do you know if there are any other ways of writing this line of code?
Cheers

You can post your code here

Hi Qudusayo
Iā€™ve posted my code below. I wasnt able to paste my entire package.json code but Iā€™m still getting this error.

npm ERR! JSON.parse Unexpected token "<" (0x3C) in JSON at position 0 while parsing near "<!DOCTYPE html>\n<htm..."
npm ERR! JSON.parse Failed to parse JSON data.
npm ERR! JSON.parse Note: package.json must be actual JSON, not just JavaScript.

HTML

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Morarables</title>

</head>

<body>

    <div>

        <button id="btnConnect">Connect Wallet</button>

        <button id="btnUserInfo">Profile</button>

        <button id="btnOpenCreateItem">Create</button>

        <button id="btnMyItems">My Items</button>

    </div>

    <div id="userInfo">

        <h4>User Profile</h4>

        <input type="text" id="txtUsername" required placeholder="Enter username">

        <input type="text" id="txtEmail" placeholder="Enter email">

        <small>Optional</small>

        <img width="50" height="50" src="" id="imgAvatar" alt="">

        <label for="fileAvatar">Select Avatar</label>

        <input type="file" id="fileAvatar">

        <button id="btnLogOut">Log out</button>

        <button id="btnCloseUserInfo">Close</button>

        <button id="btnSaveUserInfo">Save</button>

    </div>

    <div id="createItem">

        <h4>Create Item</h4>

        <input type="text" id="txtCreateItemName" required placeholder="Enter name">

        <textarea id="txtCreateItemDescription" cols="30" rows="5" placeholder="Enter description"></textarea>

        <input type="number" min="1" step="1" id="numCreateItemPrice" placeholder="Enter price" required>

        <label for="selectCreateItemStatus">Status</label>

        <select id="selectCreateItemStatus">        

            <option value="0">Not for sale</option>

            <option value="1">Instant buy</option>

            <option value="2">Accept Offers</option>

        </select>

        <label for="fileCreateItemFile">Select File</label>

        <input type="file" id="fileCreateItemFile">

        <button id="btnCloseCreateItem">Close</button>

        <button id="btnCreateItem">Create!</button>

    </div>

    <div id="userItems">

        <h4>My Items</h4>

        <div id="userItemsList"></div>

        <button id="btnCloseUserItems">Close</button>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>

    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>

    <script src="abi.js"></script>

    <script src="main.js"></script>

</body>

</html>

Javascript

const serverUrl = "https://5platkya43gg.usemoralis.com:2053/server";

const appId = "iyhSgWOnDLaSy73cTGRPT2pQ1yG6TNbwr5pzKsIo";

const TOKEN_CONTRACT_ADDRESS = "0x9a5B99bAb34FE642Bf4946F7fBA349519E0a7b31";

Moralis.start({ serverUrl, appId });

init = async () => {

    hideElement(userItemsSection);

    hideElement(userInfo);

    hideElement(createItemForm);

    await Moralis.enableWeb3();

    web3 = new Web3(web3.currentProvider);

    window.tokenContract = new web3.eth.Contract(tokenContractAbi, TOKEN_CONTRACT_ADDRESS)

     initUser();

     loadItems();

}

initUser = async () => {

    if (await Moralis.User.current()){

        hideElement(userConnectButton);

        showElement(userProfileButton);

        showElement(openCreateItemButton);

        showElement(openUserItemsButton);

    }else{

        showElement(userConnectButton);

        hideElement(userProfileButton);

        hideElement(openCreateItemButton);

        hideElement(createItemForm);

        hideElement(openUserItemsButton);

    }

}

login = async () => {

    try {

        await Moralis.authenticate();

        initUser();

    } catch (error) {

        alert(error)

    }

}

logout = async () => {

    await Moralis.User.logOut();

    hideElement(userItems);

    initUser();

}

openUserInfo = async () => {

    user = await Moralis.User.current();

    if (user){    

        const email = user.get('email');

        if(email){

            userEmailField.value = email;

        }else{

            userEmailField.value = "";

        }

        userNameField.value = user.get('username');

        const userAvatar = user.get('avatar');

        if(userAvatar){

            userAvatarImg.src = userAvatar.url();

            showElement(userAvatarImg);

        }else{

            hideElement(userAvatarImg);

        }

        showElement(userInfo);

    }else{

        login();

    }

}

saveUserInfo = async () => {

    user.set('email', userEmailField.value);

    user.set('username', userNameField.value);

    if (userAvatarFile.files.length > 0) {

        const avatar = new Moralis.File("avatar1.jpg", userAvatarFile.files[0]);

        user.set('avatar', avatar);

    }

    await user.save();

    alert("User info saved successfully!");

    openUserInfo();

}

createItem = async () => {

    if (createItemFile.files.length == 0){

        alert("Please select a file!");

        return;

    } else if (createItemNameField.value.length == 0){

        alert("Please give the item a name!");

        return;

    }

const nftFile = new Moralis.File("nftFile.webp", createItemFile.files[0]);

await nftFile.saveIPFS();

const nftFilePath = nftFile.ipfs();

const nftFileHash= nftFile.hash();

const metadata = {

    name: createItemNameField.value,

    description: createItemDescriptionField.value,

    image: nftFilePath,

};

const nftFileMetadataFile = new Moralis.File("metadata.json", {base64 : btoa(JSON.stringify(metadata))});

await nftFileMetadataFile.saveIPFS();

const nftFileMetadataFilepath = nftFileMetadataFile.ipfs();

const nftFileMetadataFileHash = nftFileMetadataFile.hash();

const nftId = await mintNft(nftFileMetadataFilepath);

const Item = Moralis.Object.extend("Item");

const item = new Item();

item.set('name', createItemNameField.value);

item.set('description', createItemDescriptionField.value);

item.set('nftFilePath', nftFilePath);

item.set('nftFileHash', nftFileHash);

item.set('metadataFilePath', nftFileMetadataFilepath);

item.set('metadataFileHash', nftFileMetadataFileHash);

item.set('nftId', nftId)

item.set('nftContractAddres', TOKEN_CONTRACT_ADDRESS);

await item.save();

console.log(item);

}

mintNft = async (metadataUrl) => {

    const receipt = await tokenContract.methods.createItem(metadataUrl).send({from: ethereum.selectedAddress});

    console.log(receipt);

    return receipt.events.Transfer.returnValues.tokenId;

}

openUserItems = async () => {

    user = await Moralis.User.current();

    if (user){    

        showElement(userItemsSection);

    }else{

        login();

    }

}

loadItems = async () => {

    const ownedItems = await Moralis.Cloud.run("getUserItems");

    console.log(loadUserItems);

}

hideElement = (element) => element.style.display = "none";

showElement = (element) => element.style.display = "block";

//Navbar

const userConnectButton = document.getElementById("btnConnect");

userConnectButton.onclick = login;

const userProfileButton = document.getElementById("btnUserInfo");

userProfileButton.onclick = openUserInfo;

//Userinfo

const userInfo = document.getElementById("userInfo");

const userNameField = document.getElementById("txtUsername");

const userEmailField = document.getElementById("txtEmail");

const userAvatarImg = document.getElementById("imgAvatar");

const userAvatarFile = document.getElementById("fileAvatar");

document.getElementById("btnCloseUserInfo").onclick = () => hideElement(userInfo)

document.getElementById("btnLogOut").onclick = logout;

document.getElementById("btnSaveUserInfo").onclick = saveUserInfo;

//Item Creation

const createItemForm = document.getElementById("createItem");

const createItemNameField = document.getElementById("txtCreateItemName");

const createItemDescriptionField = document.getElementById("txtCreateItemDescription");

const createItemPriceField = document.getElementById("numCreateItemPrice");

const createItemStatusField = document.getElementById("selectCreateItemStatus");

const createItemFile = document.getElementById("fileCreateItemFile");

const openCreateItemButton = document.getElementById("btnOpenCreateItem");

openCreateItemButton.onclick = () => showElement(createItemForm);

document.getElementById("btnCloseCreateItem").onclick = () => hideElement(createItemForm);

document.getElementById("btnCreateItem").onclick = createItem;

//User items

const userItemsSection = document.getElementById("userItems");

const userItems = document.getElementById("userItemsList");

document.getElementById("btnCloseUserItems").onclick = () => hideElement(userItemsSection)

const openUserItemsButton = document.getElementById("btnMyItems");

openUserItemsButton.onclick = openUserItems;

init();

Abi.js

var tokenContractAbi = [

      {

        "inputs": [],

        "stateMutability": "nonpayable",

        "type": "constructor"

      },

      {

        "anonymous": false,

        "inputs": [

          {

            "indexed": true,

            "internalType": "address",

            "name": "owner",

            "type": "address"

          },

          {

            "indexed": true,

            "internalType": "address",

            "name": "approved",

            "type": "address"

          },

          {

            "indexed": true,

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          }

        ],

        "name": "Approval",

        "type": "event"

      },

      {

        "anonymous": false,

        "inputs": [

          {

            "indexed": true,

            "internalType": "address",

            "name": "owner",

            "type": "address"

          },

          {

            "indexed": true,

            "internalType": "address",

            "name": "operator",

            "type": "address"

          },

          {

            "indexed": false,

            "internalType": "bool",

            "name": "approved",

            "type": "bool"

          }

        ],

        "name": "ApprovalForAll",

        "type": "event"

      },

      {

        "anonymous": false,

        "inputs": [

          {

            "indexed": true,

            "internalType": "address",

            "name": "from",

            "type": "address"

          },

          {

            "indexed": true,

            "internalType": "address",

            "name": "to",

            "type": "address"

          },

          {

            "indexed": true,

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          }

        ],

        "name": "Transfer",

        "type": "event"

      },

      {

        "inputs": [

          {

            "internalType": "uint256",

            "name": "",

            "type": "uint256"

          }

        ],

        "name": "Items",

        "outputs": [

          {

            "internalType": "uint256",

            "name": "id",

            "type": "uint256"

          },

          {

            "internalType": "address",

            "name": "creator",

            "type": "address"

          },

          {

            "internalType": "string",

            "name": "uri",

            "type": "string"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      },

      {

        "inputs": [

          {

            "internalType": "address",

            "name": "to",

            "type": "address"

          },

          {

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          }

        ],

        "name": "approve",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

      },

      {

        "inputs": [

          {

            "internalType": "address",

            "name": "owner",

            "type": "address"

          }

        ],

        "name": "balanceOf",

        "outputs": [

          {

            "internalType": "uint256",

            "name": "",

            "type": "uint256"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      },

      {

        "inputs": [

          {

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          }

        ],

        "name": "getApproved",

        "outputs": [

          {

            "internalType": "address",

            "name": "",

            "type": "address"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      },

      {

        "inputs": [

          {

            "internalType": "address",

            "name": "owner",

            "type": "address"

          },

          {

            "internalType": "address",

            "name": "operator",

            "type": "address"

          }

        ],

        "name": "isApprovedForAll",

        "outputs": [

          {

            "internalType": "bool",

            "name": "",

            "type": "bool"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      },

      {

        "inputs": [],

        "name": "name",

        "outputs": [

          {

            "internalType": "string",

            "name": "",

            "type": "string"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      },

      {

        "inputs": [

          {

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          }

        ],

        "name": "ownerOf",

        "outputs": [

          {

            "internalType": "address",

            "name": "",

            "type": "address"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      },

      {

        "inputs": [

          {

            "internalType": "address",

            "name": "from",

            "type": "address"

          },

          {

            "internalType": "address",

            "name": "to",

            "type": "address"

          },

          {

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          }

        ],

        "name": "safeTransferFrom",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

      },

      {

        "inputs": [

          {

            "internalType": "address",

            "name": "from",

            "type": "address"

          },

          {

            "internalType": "address",

            "name": "to",

            "type": "address"

          },

          {

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          },

          {

            "internalType": "bytes",

            "name": "_data",

            "type": "bytes"

          }

        ],

        "name": "safeTransferFrom",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

      },

      {

        "inputs": [

          {

            "internalType": "address",

            "name": "operator",

            "type": "address"

          },

          {

            "internalType": "bool",

            "name": "approved",

            "type": "bool"

          }

        ],

        "name": "setApprovalForAll",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

      },

      {

        "inputs": [

          {

            "internalType": "bytes4",

            "name": "interfaceId",

            "type": "bytes4"

          }

        ],

        "name": "supportsInterface",

        "outputs": [

          {

            "internalType": "bool",

            "name": "",

            "type": "bool"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      },

      {

        "inputs": [],

        "name": "symbol",

        "outputs": [

          {

            "internalType": "string",

            "name": "",

            "type": "string"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      },

      {

        "inputs": [

          {

            "internalType": "address",

            "name": "from",

            "type": "address"

          },

          {

            "internalType": "address",

            "name": "to",

            "type": "address"

          },

          {

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          }

        ],

        "name": "transferFrom",

        "outputs": [],

        "stateMutability": "nonpayable",

        "type": "function"

      },

      {

        "inputs": [

          {

            "internalType": "string",

            "name": "uri",

            "type": "string"

          }

        ],

        "name": "createItem",

        "outputs": [

          {

            "internalType": "uint256",

            "name": "",

            "type": "uint256"

          }

        ],

        "stateMutability": "nonpayable",

        "type": "function"

      },

      {

        "inputs": [

          {

            "internalType": "uint256",

            "name": "tokenId",

            "type": "uint256"

          }

        ],

        "name": "tokenURI",

        "outputs": [

          {

            "internalType": "string",

            "name": "",

            "type": "string"

          }

        ],

        "stateMutability": "view",

        "type": "function",

        "constant": true

      }

    ]

package.json

<!DOCTYPE html>

<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system">

  <head>

    <meta charset="utf-8">

  <link rel="dns-prefetch" href="https://github.githubassets.com">

  <link rel="dns-prefetch" href="https://avatars.githubusercontent.com">

  <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">

  <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">

  <link rel="preconnect" href="https://github.githubassets.com" crossorigin>

  <link rel="preconnect" href="https://avatars.githubusercontent.com">

  <link crossorigin="anonymous" media="all" integrity="sha512-ksfTgQOOnE+FFXf+yNfVjKSlEckJAdufFIYGK7ZjRhWcZgzAGcmZqqArTgMLpu90FwthqcCX4ldDgKXbmVMeuQ==" rel="stylesheet" href="https://github.githubassets.com/assets/light-92c7d381038e.css" /><link crossorigin="anonymous" media="all" integrity="sha512-1KkMNn8M/al/dtzBLupRwkIOgnA9MWkm8oxS+solP87jByEvY/g4BmoxLihRogKcX1obPnf4Yp7dI0ZTWO+ljg==" rel="stylesheet" href="https://github.githubassets.com/assets/dark-d4a90c367f0c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" integrity="sha512-cZa7DZqvMBwD236uzEunO/G1dvw8/QftyT2UtLWKQFEy0z0eq0R5WPwqVME+3NSZG1YaLJAaIqtU+m0zWf/6SQ==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-7196bb0d9aaf.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" integrity="sha512-WVoKqJ4y1nLsdNH4RkRT5qrM9+n9RFe1RHSiTnQkBf5TSZkJEc9GpLpTIS7T15EQaUQBJ8BwmKvwFPVqfpTEIQ==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-595a0aa89e32.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" integrity="sha512-XpAMBMSRZ6RTXgepS8LjKiOeNK3BilRbv8qEiA/M3m+Q4GoqxtHedOI5BAZRikCzfBL4KWYvVzYZSZ8Gp/UnUg==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-5e900c04c491.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" integrity="sha512-3HF2HZ4LgEIQm77yOzoeR20CX1n2cUQlcywscqF4s+5iplolajiHV7E5ranBwkX65jN9TNciHEVSYebQ+8xxEw==" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-dc71761d9e0b.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" integrity="sha512-+J8j3T0kbK9/sL3zbkCfPtgYcRD4qQfRbT6xnfOrOTjvz4zhr0M7AXPuE642PpaxGhHs1t77cTtieW9hI2K6Gw==" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-f89f23dd3d24.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" integrity="sha512-AQeAx5wHQAXNf0DmkvVlHYwA3f6BkxunWTI0GGaRN57GqD+H9tW8RKIKlopLS0qGaC54seFsPc601GDlqIuuHg==" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-010780c79c07.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" integrity="sha512-+u5pmgAE0T03d/yI6Ha0NWwz6Pk0W6S6WEfIt8veDVdK8NTjcMbZmQB9XUCkDlrBoAKkABva8HuGJ+SzEpV1Uw==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-faee699a0004.css" />

 

    <link crossorigin="anonymous" media="all" integrity="sha512-EAhBCLIJ/pXHG3Y6yQhs9s53SHV80sjJ+yCwlQtfv7LaVkD+VoEuZBZ5betQJFUNj/5qBSfZk5GFtazEDzWLAg==" rel="stylesheet" href="https://github.githubassets.com/assets/primer-10084108b209.css" />

    <link crossorigin="anonymous" media="all" integrity="sha512-gm6W+V8XSAJKeuEiQ5g/Kiyre5DLBXcmbqtkNSPtTclKp78KeC0vPyQJKO3QBPSAOAsGtkNerBwQwxFAjGTg7w==" rel="stylesheet" href="https://github.githubassets.com/assets/global-826e96f95f17.css" />

    <link crossorigin="anonymous" media="all" integrity="sha512-QVHRvU+lsiBTT0dePas9QeGUp/AUz8nmg5MOU5vTdzbvu8eEamPp51Zk/H9qsm70vBgDWe3fXKUDoxAs3pOe0g==" rel="stylesheet" href="https://github.githubassets.com/assets/github-4151d1bd4fa5.css" />

Your ā€œpackage.jsonā€ isnā€™t correct, that code should be in another .html file. Which part of the tutorial are you following for this?

The rest of your app (index.html, main.js, abi.js) runs normally outside of a few errors e.g. Cannot read properties of undefined (reading 'attributes').

Hi Glad
Iā€™m upto part 8 of the tutorial for cloud functions. I couldnā€™t get a cloud function response in the console like the video had and I was told to try uninstalling everything and reinstalling to see if that fixs it. Iā€™ve done that and everything works again on the app except for my truffle migrate. I keep getting this json error.
My ā€œpackage.jsonā€ code should be in my html file?
Cheers :slight_smile:

<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system">

  <head>

    <meta charset="utf-8">

  <link rel="dns-prefetch" href="https://github.githubassets.com">

This code is not JSON, it is HTML, so it shouldnā€™t be in a file called package.json (this package.json file is for a different type of project environment and typically not used for one using static .html and .js files). Can you give the timestamp of the video where this is explained? In part 8, I cannot see where this code is meant to come from.

In which folder are you running truffle migrate? It is not related to any of the code you have posted e.g. there is no contract code.

Ok
1 minute into video 6 is where the code truffle init is done and the importing of open zeppelin. Thats how i got the package.json file. I havenā€™t changed anything in that file yet i just get a error for it.
Iā€™m trying to migrate in the frontend folder.
Cheers

Ok but you canā€™t use that same package.json with that HTML code. It sounds like you are missing steps. E.g. truffle migrate needs to be run in your Truffle project directory (or where the contracts/migrations folders are).

<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system">

  <head>

    <meta charset="utf-8">

  <link rel="dns-prefetch" href="https://github.githubassets.com">

Where does this code come from in the tutorial (part, timestamp) ?

Yes I might of missed a step and that code was there already once I got the package.json file. I never wrote that piece of code. ill backtrack the videos and see what i missed :slight_smile:

Hi Glad
Iā€™ve gone back and Iā€™m installing openzeppelin again which says it works but nothing gets added on under contracts? I was putting npm install @openzeppelin/contracts in the terminal
Screenshot of side bar for openzeppelin

Iā€™ve fixed the issue :slight_smile: