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?
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);
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)}
Related
I am fairly new to this and please let me know if I am wrong in any point.
I am trying to convert WEI into Eth, without using the Web3 library.
const weiValue = 100000;
const ethValue = ethers.utils.formatEther(weiValue);<--- answer is correct at 0.0000000000001
My code requires me to change 40000000000000000 wei to eth.
and here is what I have:
const weiValue = 40000000000000000;
const tokenRateString = tokenRate.toString();
const ethValue = ethers.utils.formatEther();
I believe I need to convert the Wei into a string as it too large to be represented accurately as integers in JS
I am confused on what is the intermediate step here
To who ever comes here later.
Yes, a big number such like this : 40000000000000000 need to be a string.
What you need to do is this: 40000000000000000
const WeiToEth = (tokenRate)=> {
const weiValue = BigNumber.from("40000000000000000");
const ethValue = ethers.utils.formatEther(weiValue);
console.log(ethValue) }
It converts the number into a string
Here is the documentation : https://docs.ethers.io/v5/api/utils/bignumber/
I have extracted the schema of my BigQuery table from the "INFORMATION_SCHEMA" table. I get the list of all the columns in the table in a proper Javascript Object format except of the "Struct" and "Array" data types. I need a clean way to convert the "Struct" and "Array" string into a javascript object.
I am working with NodeJS v11.2 I have written a small regex which extracts the following. But it doesn't seem right to split the string and iterate through each word until I get the output. I need a cleaner way to solve this.
let structString = "STRUCT<name STRING, email STRING, time_sec INT64, tz_offset INT64, date STRUCT<seconds INT64, nanos INT64>>";
let _structSchema = structString.match(/STRUCT<([^)]+)>/)[1];
console.log(_structSchema); // name STRING, email STRING, time_sec INT64, tz_offset INT64, date STRUCT<seconds INT64, nanos INT64>
I need to write a recursive function which will parse though the string and give me the output in following manner.
{
"name": "STRING",
"email": "STRING",
"time_sec": "INT64",
"tz_offset": "INT64",
"date": {
"seconds": "INT64",
"nanos": "INT64"
}
}
The function should run irrespective of the depth/hierarchy of the nested structs/arrays.
Using a regex can be good to tokenise the input string, but you'll need more logic to perform the actual parsing.
Here is how you could do it:
function parse(structString) {
let tokenizer = /([a-z_]\w*)|\S|$/gi;
function next(identifier, expected) {
let match = tokenizer.exec(structString);
function error(expected) {
throw `Expected ${expected} but got ${match[0]} at ${match.index}`;
}
match[0] = match[0] || "<EOF>";
if (identifier && !match[1]) error(identifier);
if (expected && !expected.includes(match[0])) error(expected.join(" or "))
return match[0];
}
function getType() {
let fieldType = next("type identifier or STRUCT or ARRAY");
if (fieldType === "STRUCT") {
next(null, ["<"]);
fieldType = {};
do {
fieldType[next("field identifier")] = getType();
} while (next(null, [",", ">"]) === ",");
} else if (fieldType === "ARRAY") {
next(null, ["<"]);
fieldType = [getType()];
next(null, [">"]);
}
return fieldType;
}
let result = getType();
next(null, ["<EOF>"]);
return result;
}
// Sample input & call
let structString = "STRUCT<name STRING, email STRING, time_sec INT64, tz_offset INT64, date STRUCT<seconds INT64, nanos INT64>, phones ARRAY<STRING>>";
let obj = parse(structString);
console.log(obj);
If you can access Google Cloud Console from your environment, consider running something like: bq show --format=pretty project:dataset.table or bq show --format=prettyjson project:dataset.table. You would still need to parse the results for your purposes, but the nesting is already done for you.
Conside I have a JSON like this(Example: { "abcd":"abcd" ).
I forgot to add braces at the end and its in minified format. I need to convert this into beautify JSON even its invalid using JavaScript like mentioned below
{
\n\t "abcd":"abcd"
Is there any solutions in JavaScript or TypeScript
Actual:
{ "abcd": "abcd","decs": { "jan": 1, "feb" :2 }
Expected:
{
\n\t "abcd": "abcd",
\n\t "decs":
\n {
\n\t\t "jan":1,
\n\t\t "feb":2
\n\t }
I will assume that your JSON is stored in a variable.
let json = '{ "abcd": "abcd","decs": { "jan": 1, "feb" :2 }';
If you don't know what let is, use var.
Then you can do:
json += '}';
And to verify it:
console.log( JSON.parse(json) );
My csv looks like this:
year,dybde,snavn,sfylke
1965,110,Oslo,Sogn og Fjordane
1966,176,Krutå fjellstue,Sogn og Fjordane
1967,86,Ytre Sandsvær,Sogn og Fjordane
This returns NaN for the snavn and sfylke values:
d3.csv("data.csv", function(error, data) {
data.forEach(function(d){
d.year = +d.year;
d.dybde = +d.dybde;
d.snavn = +d.snavn;
d.sfylke = +d.sfylke;
});
sdata = data;
console.log(sdata);
});
I've tried putting the strings in quotes, but it still returns NaN.
Any ideas to point out the mistake would be very much appreciated.
Code something = +strVar always returns NaN - it's impossible to directly convert string to int, so it's Not a Number.
If you want to convert every string to 0, you have to write something = strVar|0.
Or just remove sign + from these lines:
d.snavn = +d.snavn;
d.sfylke = +d.sfylke;
I have this Json string that i use for google chart visualization that needs to be in this exact format and i need to replace every value of "v" that is a number to its numeric value( the value without the ""). I should do some javascript replace function, but i couldn't find a way to move around the json object. Here is and example json string that i should modify :
{"cols":[
{"id":"r","label":"Reason","type":"string"},
{"id":"m","label":"Minutes","type":"number"}
],
"rows":[
{"c":[
{"v":"Flour - Blower","f":"Flour - Blower"},
{"v":"7","f":"7"}]},
{"c":[
{"v":"Whole Line - d","f":"Whole Line - d"},
{"v":"4","f":"4"}]},
{"c":[
{"v":"Flour - Pipework","f":"Flour - Pipework"},
{"v":"3","f":"3"}]},
{"c":[
{"v":"Horseshoe - Belt","f":"Horseshoe - Belt"},
{"v":"1","f":"1"}]}
],
"p":null
}
probably i should do something like :
var jsonStr = ...;
for (i in jsonStr.rows) {
for(j in jsonStr[i].c)
{
if (parseInt(jsonStr[i].c[j].v) != 'NaN') {
jsonStr.rows[i].c[j].v = parseInt(jsonStr.rows[i].c[j].v);
}
}
Since JSON is effectively a string, why not put the entire string through a global string.replace:
jsonStr = JSON.stringify(jsonStr);
jsonStr = jsonStr.replace(/"v":"(\d+)"/g, '"v":$1');
Jsfiddle demo
Well, the parsing seems okay to me. It's probably not working because you can't really check if a string contains a number or not by comparing something with NaN
This is because even NaN === NaN, famously, returns false.
I'd suggest that you use the isNaN method (which does use parseInt internally). So, something like this ought to work
for (i in jsonStr.rows) {
for(j in jsonStr[i].c)
{
if (!isNaN(jsonStr[i].c[j].v)) {
jsonStr.rows[i].c[j].v = parseInt(jsonStr.rows[i].c[j].v);
}
}
A function that returns string if isNaN else a number:
function convertNumberToInteger(val) {
if (isNaN(val)) {
return val;
} else {
return parseInt(val);
}
}
Usage:
convertNumberToInteger("sasdfasdf");
Output: "sasdfasdf"
convertNumberToInteger("3");
Output: 3
And if you really want to parse it you can do a forEach on the JSON object