Home > Software engineering >  String to JavaScript JSON/Object
String to JavaScript JSON/Object

Time:12-04

I have string like array and object want to convert it to pure javascript object or JSON.

My string example:

"`{keyOne: valueOne, KeyTow: [10, true, null, 10%], keyThree: {hello: hi}}`"

I found a solution converting string to JSON here https://stackoverflow.com/a/42907123/4578250

the result with above solution is:

{"keyOne": "valueOne", "KeyTow": [10, true, null, "10"%], "keyThree": {"hello": "hi"}}

I want the result like:

{"keyOne": "valueOne", "KeyTow": [10, true, null, "10%"], "keyThree": {"hello": "hi"}}

But I'm not able to convert the string with percentage symbol. any help will be appreciated.

CodePudding user response:

Just quote all alphanumeric sequences, except for those that are true, false, null, or a number:

let s = "`{keyOne: valueOne, KeyTow: [10, true, null, 10%], keyThree: {hello: hi}}`"

let r = s.replaceAll('`', '').replaceAll(/([\w%] )/g, m =>
  m.match(/^\d[\d.]*$/) || ['true','false','null'].includes(m) ? m : `"${m}"`)

console.log(JSON.parse(r))

  • Related