-1

I am trying to convert a quote number to a string, inside a JSON.stringify()

The number is behaving like a BIGINT so it cannot be changed after parsing

When parsed as an INT the number 950375379233915148 turns into 950375379233915100

let json=  "[{\"IDItem\":1111111,\"ItemName\":\"Test\",\"startDate\":\"Aug 31 2020 12:00AM\",\"FinishtDate\":\"Aug 31 2020 12:00AM\",\"startTime\":\"10:30:00.0000000\",\"itemNum\":123564554,\"Place\":\"10\",\"IDItemType\":30,\"Remark\":null,\"SmooveId\":0,\"WebinarKey\":950375379233915148,\"FullDescription\":null,\"ItmCode\":\"TE\",\"isPublic\":false,\"ActiveUserID\":1}]"

Trying to replace by regex:

json.replace(/WebinarKey":(\d.+),/, "WebinarKey\":\"$1\",")

That's what I get:

"[{
"IDItem":1111111,
"ItemName":"Test",
"startDate":"Aug 31 2020 12:00AM",
"FinishtDate":"Aug 31 2020 12:00AM",
"startTime":"10:30:00.0000000",
"itemNum":123564554,
"Place":"10",
"IDItemType":30,
"Remark":null,
"SmooveId":0,
"WebinarKey":"950375379233915148,"FullDescription":null,"ItmCode":"TE","isPublic":false",
"ActiveUserID":1
}]"

The replace function converts the string of all variables starting from "WebinarKey" to "isPublic" i.e. it adds the quote after false"

and I just want to convert the variable "WebinarKey" content to string

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Julio
  • 355
  • 1
  • 4
  • 14
  • Try `(\d+)` instead of `(\d.+)`. *Note* This is not a recommended way – User863 Aug 25 '20 at 08:34
  • @Liam if I convert the json into an object, the number that is in the WebinarKey would change to something like this "3669516009270899000" because it is a BigInt, that is why I need to convert it to a string before converting it to an object – Julio Aug 25 '20 at 08:42

1 Answers1

1

The BEST solution is to make the producers of this JSON fix their string

To solve your RegEx issue, you need to make the regex lazy instead of greedy

So (\d.+?), or (\d+?), instead of (\d.+),

let json=  "[{\"IDItem\":1111111,\"ItemName\":\"Test\",\"startDate\":\"Aug 31 2020 12:00AM\",\"FinishtDate\":\"Aug 31 2020 12:00AM\",\"startTime\":\"10:30:00.0000000\",\"itemNum\":123564554,\"Place\":\"10\",\"IDItemType\":30,\"Remark\":null,\"SmooveId\":0,\"WebinarKey\":950375379233915148,\"FullDescription\":null,\"ItmCode\":\"TE\",\"isPublic\":false,\"ActiveUserID\":1}]"

let changed = json.replace(/WebinarKey":(\d.+?),/, 'WebinarKey":"$1",')
console.log(JSON.parse(changed))

// if only numbers in the field

changed = json.replace(/WebinarKey":(\d+?),/, 'WebinarKey":"$1",')
console.log(JSON.parse(changed))
mplungjan
  • 169,008
  • 28
  • 173
  • 236