简体   繁体   中英

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().

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);

JSON text/object can be converted into Javascript object using the function JSON.parse()

 var object = JSON.parse('{"attribute":value, "attribute2":0}'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM