Home > Blockchain >  Replace new JSON in javascript
Replace new JSON in javascript

Time:02-02

I want to make JSON look like this:

{"tokenId":1,"uri":"ipfs://bafy...","minPrice":{"type":"BigNumber","hex":"0x1a"},"signature":"0x51xxx"}

This is my currently output:

 {
        "tokenId": "1",
        "uri": "ipfs://baf...",
        "minPrice": 0.26,
        "signature": "0x..."
    }

This is the retrieve code.

async function redeem(cid) {
  fetch(`http://localhost:4000/getDetails/${cid}`).then(response => {
    return response.json()
  }).then((async output=> {
    console.log(output[0]); // it displays json
    const obj = output[0].minPrice.toString();
    const price = ethers.utils.parseUnits(obj,2);
    console.log(price) 
  }))

 

I want to make the minPrice look same as the above, so I use ethers.utils.parseUnits. After converting it, how can I replace the existing minPrice with the BigNumber minPrice(price) so the JSON output will look exactly like the first JSON?

CodePudding user response:

You can convert your number minPrice to a hex string by specifying the radix:

minPrice.toString(16)

so probably you want something like

price.minPrice = {"type": "BigNumber","hex": price.minPrice.toString(16)}

CodePudding user response:

Convert the price to an integer by multiplying by 100. Then convert that to hex.

let price_cents = Math.round(output[0].minPrice * 100);
let hex_price = '0x'   price_cents.toString(16);
  • Related