Reputation: 344
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().
Upvotes: 4
Views: 4395
Reputation: 23778
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);
Upvotes: 3
Reputation: 7
JSON text/object can be converted into Javascript object using the function JSON.parse()
var object = JSON.parse('{"attribute":value, "attribute2":0}');
Upvotes: -1