Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove single quotes from around the properties of a json string

I need a correct and easy way to convert a JSON String to object (javascript code string), like:

"'attribute': {
  'attribute': 'value',
  'attribute2': 0
}"

to

"attribute: {
  attribute: 'value',
  attribute2: 0
}"

The thing is remove the ' around the attribute.

The porpose of this is to help convert a object to a javascript code using the JSON.stringfy().

like image 429
Forsaiken Avatar asked Sep 08 '25 09:09

Forsaiken


1 Answers

This regex can remove single quotes from around the property names. There will be some extreme cases that would not be working with this regex. But for simple objects as cited in your question, this is good.

var jsonstr = "{  'attribute': 'value',  'attribute2': 0, 'parentattr': {'x': 0}} ";

jsonstr = jsonstr.replace(/'([^']+)':/g, '$1:');

console.log(jsonstr);
like image 138
Charlie Avatar answered Sep 10 '25 07:09

Charlie