Say if I have a object:
{ "name": "abc", "profession": null, "createdOn": "2022-01-05 10:00:05" }
,
when I convert it to a string, I need output like:
'{"name">"abc", "profession">nil, "createdOn">"2022-01-05 10:00:05" }
If I global replace like:
JSON.stringify(inputObject).replace(/null/g, 'nil').replace(/:/g, '>')
,
I will get:
{"name">"abc", "profession">nil, "createdOn">"2022-01-05 10>00>05" }
There are couple of problems here:
- It replaces all the instances of
:
, whereas I need to replace the ones in front of key names only (like key:
value) - Though replacement of
null
tonil
is working, ifprofession
was"profession": "null blah"
, it would make it"profession">"nil blah"
. I don't want to modify if the value is notnull
.
Is there a better way to handle above scenarios?
CodePudding user response:
The simple solution may be:
const a = {
name: 'abc',
gender: 'null',
gender2: 'my null value',
profession: null,
createdOn: '2022-01-05 10:00:05',
};
const b = JSON.stringify(a)
.replace(/":/g, '">')
.replace(/">null/g, '">nil')
;
console.log(b);
Output:
{"name">"abc","gender">"null","gender2">"my null value","profession>nil,"createdOn
">"2022-01-05 10:00:05"}
CodePudding user response:
function format(inputObject) {
if (inputObject) {
if (typeof inputObject === "object" && !Array.isArray(inputObject)) {
const objectEntries = Object.entries(inputObject);
if (objectEntries.length) {
const reformatted =
objectEntries
.map(([key, value]) => `"${key}">${!value ? 'nil' : "\"" value "\""}`)
.join(",") || "";
return `{${reformatted}}`;
}
return "{}";
}
}
return `${inputObject}`;
}
Illustration
const obj = {
"name": "abc",
"profession": null,
"createdOn": "2022-01-05 10:00:05"
};
function format(inputObject) {
if (inputObject) {
if (typeof inputObject === "object" && !Array.isArray(inputObject)) {
const objectEntries = Object.entries(inputObject);
if (objectEntries.length) {
const reformatted =
objectEntries
.map(([key, value]) => `"${key}">${!value ? 'nil' : "\"" value "\""}`)
.join(",") || "";
return `{${reformatted}}`;
}
return "{}";
}
}
return `${inputObject}`;
}
console.log(format(obj));