0

I have below json data I need to replace "=" to ":" by Javascript

{ "name"="John", "age"=30, "car"=null }

Expected output:

{ "name":"John", "age":30, "car":null }
contactMon
  • 76
  • 1
  • 8
  • Possible duplicate of [JavaScript - Replace all commas in a string](https://stackoverflow.com/questions/10610402/javascript-replace-all-commas-in-a-string) – GenericUser Jan 12 '19 at 13:47
  • That's not a valid json string. You can play around with `replace` but it's better to fix how that json is generated. Every language has a method to convert an object json string. – adiga Jan 12 '19 at 13:53

3 Answers3

2

This should do the trick:

var str = '{ "name"="John", "age"=30, "car"=null }';
str = str.replace(/=/g,":");

var json = JSON.parse(str);

Note, that it would convert ALL "=" to ":". If there can be symbol in name or value, different approach should be used.

-- Update "g" modifier has to be used if there is more than one "=" to replace.

jancha
  • 4,916
  • 1
  • 24
  • 39
0

Use g flag:

'{ "name"="John", "age"=30, "car"=null }'.replace(/\=/g, ':')
Beniamin H
  • 2,048
  • 1
  • 11
  • 17
0

You can use Replace

let op = `{ "name"="John", "age"=30, "car"=null }`.replace(/=/g, ':')

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60