简体   繁体   中英

Validate and format a JavaScript object to a JSON format

I have to send a given javascript object from angular to backend(nestJS),

{
      service: {
        port: 3080,
      },
      datasource: {
        m3: {
          rest: {
            url: 'https://se/',
            username: 'di.com',
            password: 'B4',
          },
        },
        postgraphile: {
          url: 'https://gl',
          hostname: 'sg',
          port: 1133,
          database: 'MV',
          username: 'rr',
          password: '1',
        },
      },
      database: {
        pg: {
          hostname: 'ss.com',
          port: 5432,
          username: 'br',
          password: '1x',
          database: 'eb',
          synchronize: false,
        },
        mssql: {
          hostname: '10.100.100.100',
          port: 1133,
          database: 'MV',
          schema: 'MA',
          username: 'rr',
          password: 'we',
        },
        redis: {
          url: 'redis:///0',
        },
      },
      graphql: {
        playground: true,
      },
    }

I tried to make this a JSON object in order to send the data,

var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;// look for object names
var newQuotedKeysString = b.replace(objKeysRegex, "$1\"$2\":");// all object names should be double quoted
console.log(newQuotedKeysString);

I got the expected outcome but unable to make it a proper JSON string, due to trailing commas which there is no value after some commas. The output I got was:

{"service": {"port": 3080,
      },"datasource": {"m3": {"rest": {"url": "https://se/","username": "di.com","password": "B4",
          },
        },"postgraphile": {"url": "https://gl","hostname": "sg","port": 1133,"database": "MV","username": "rr","password": "1",
        },
      },"database": {"pg": {"hostname": "ss.com","port": 5432,"username": "br","password": "1x","database": "eb","synchronize": false,
        },"mssql": {"hostname": "10.100.100.100","port": 1133,"database": "MV","schema": "MA","username": "rr","password": "we",
        },"redis": {"url": "redis:///0",
        },
      },"graphql": {"playground": true,
      },
    }

Is there any other way apart from this, or any idea about making it a valid JSON format.

To convert a JavaScript object to a JSON string, do:

let str = JSON.stringify(obj);

First we need to Get the JavaScript Object (Nested Object) and surround the key values in the object with double quotes "" and validate for trailing commas.

For that,

//replace '' with "".
let confJsonvalue = obj.replace(/'/g, '"');

//replace trailling comma
let regex = /\,(?=\s*?[\}\]])/g;
let sanitized = confJsonvalue.replace(regex, '');

let objKeysRegex =/({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g; // look for object names
let newQuotedKeysString = sanitized.replace(objKeysRegex, '$1"$2":'); // all object names/Keys should be double quoted.

JSON.parse(newQuotedKeysString);

Using JSON.stringify(obj); will only surround the object with double quotes and return a string. (for nested JavaScript objects this is not enough).

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