Home > database >  Modify JSON string
Modify JSON string

Time:03-13

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:

  1. It replaces all the instances of :, whereas I need to replace the ones in front of key names only (like key:value)
  2. Though replacement of null to nil is working, if profession was "profession": "null blah", it would make it "profession">"nil blah". I don't want to modify if the value is not null.

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


WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

  • Related