contactMon
contactMon

Reputation: 76

How do I replaceAll character from json string using javascript

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 }

Upvotes: 0

Views: 7940

Answers (3)

Code Maniac
Code Maniac

Reputation: 37755

You can use Replace

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

console.log(op)

Upvotes: 0

Beniamin H
Beniamin H

Reputation: 2086

Use g flag:

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

Upvotes: 0

jancha
jancha

Reputation: 4967

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.

Upvotes: 2

Related Questions