Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
Modify JSON string

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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"}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda