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.
2
Answers
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,
Using JSON.stringify(obj); will only surround the object with double quotes and return a string. (for nested JavaScript objects this is not enough).
To convert a JavaScript object to a JSON string, do: