最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Stringify numbers in json as hex (or other) fomat using Javascript - Stack Overflow

programmeradmin0浏览0评论

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 of JSON.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
Add a ment  | 

2 Answers 2

Reset to default 2

You 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))

发布评论

评论列表(0)

  1. 暂无评论