4

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

Charlie
  • 22,886
  • 11
  • 59
  • 90
Forsaiken
  • 324
  • 3
  • 12
  • 1
    [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)? – Alexander Nied Jun 16 '20 at 03:07
  • Does this answer your question? [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – michaeldel Jun 16 '20 at 03:09
  • No, it's a bit confusing but I'm trying to remove the `"` around the attribute name in all JSON string. – Forsaiken Jun 16 '20 at 03:11
  • I'm curious as to the circumstances that require you to do this, if you are able to share. – Alexander Nied Jun 16 '20 at 03:45
  • 1
    @AlexanderNied Basically I'm working with Data Dictionary (front-end) mapping the properties in a object that was generated by UI, then I convert this object in a javascript code to generate a javascript file. – Forsaiken Jun 16 '20 at 04:59
  • The mortal way to do it: https://csvjson.com/json_beautifier – Moses Aprico Apr 17 '23 at 06:53

2 Answers2

3

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);
Charlie
  • 22,886
  • 11
  • 59
  • 90
-1

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

 var object = JSON.parse('{"attribute":value, "attribute2":0}'); 
Truclehy
  • 7
  • 2
  • I'm not trying to convert string to object. I'm trying to convert string (JSON) to string (Object Javascript typed in Code) – Forsaiken Jun 16 '20 at 03:17