-2

I get a string: "{ a: '123', b: '234'}", I want to make it to be "{ "a": "123", "b": "234" }" by using regex expression. Could anyone explain/guide me how do I do this? The following is my trial.

str.replace(/[']/,'"').replace(/(['"])?([a-z0-9A-Z_\-]+)(['"])?\s*:/g, '"$2":')
Cœur
  • 37,241
  • 25
  • 195
  • 267
Tel lui
  • 139
  • 1
  • 2
  • 13

2 Answers2

2

Just use JSON.parse. That's what it's made for.

Aron
  • 8,696
  • 6
  • 33
  • 59
  • 6
    But `"{ a: '123', b: '234'}"` is no valid JSON – Andreas Mar 17 '17 at 10:05
  • I actually want the JSON to BE {"a":, "123", "b": "234"}. I don't understand why the topic is down voted. – Tel lui Mar 17 '17 at 10:12
  • @Tellui you've just put a comma after the `a:`. Is that intentional? Because of your (maybe) typos it's difficult to understand what you're after: a parser for faulty JSON or just a regular JSON parser? – Aron Mar 17 '17 at 10:14
  • Okay. Let me make these all more clear :) by editing. – Tel lui Mar 17 '17 at 10:15
1

Try this code:

var yourjson = "{ a: '123', b: '234'}";
var jsontemp = yourjson.replace((/([\w]+)(:)/g), "\"$1\"$2");
var correctjson = jsontemp.replace((/'/g), "\"");
alert(correctjson);

jsfiddle

Ali Hesari
  • 1,821
  • 5
  • 25
  • 51