Is there an easy way to stringify numbers as hex format using JSON.stringify? For example if I have a JSON structure:
{
number: 1024
}
In this case I want the JSON string output to look like
{
number: 0x400
}
JSON.stringify always returns numbers in decimal format (base 10).
Is there an easy way to stringify numbers as hex format using JSON.stringify? For example if I have a JSON structure:
{
number: 1024
}
In this case I want the JSON string output to look like
{
number: 0x400
}
JSON.stringify always returns numbers in decimal format (base 10).
Share Improve this question asked Feb 19, 2019 at 11:49 AlkoAlko 79110 silver badges21 bronze badges 2-
1
0x...
formatted numbers are not valid JSON. You'd have to use the replacer function ofJSON.stringify
to format the number to a string"0x..."
.Why do you want this? – phuzi Commented Feb 19, 2019 at 12:23 - @phuzi I'm playing around with Ethereum particularly I have an issue with RPC patibility using the same call on Geth or Parity. – Alko Commented Feb 19, 2019 at 12:36
2 Answers
Reset to default 2You can use replacer
of JSON.stringify
replacer gets two parameter key
and value
being stringifed. in this function as you wanted to change number type from decimal to hex, so we check if the type is number we convert it to hex using toString()
method with base 16
and if not than we return the value directly without any change.
const obj = { num1:1024,num2:1025,num3:1026,num4:1027 }
console.log(JSON.stringify(obj, (key, value) => {
if( typeof value === 'number'){
return '0x' + value.toString(16)
}
return value
}))
You can use .toString(16)
with your number.
var obj = {
num1: 1024,
num2: 1025,
num3: 1026,
num4: 1027
}
Object.keys(obj).forEach(e => obj[e] = "0x" + obj[e].toString(16))
console.log(JSON.stringify(obj))