Convert string of ex-object to object Javascript

Viewed 20

I have a string that I got through fs.readFile of a js file.

const content = "{ host: env("HOST", "0.0.0.0"), port: env.int("PORT", 1337), app: { keys: env.array("APP_KEYS"), },}"

I need to convert it back to an object so I can check some things and re-write the file if needed.

JSON.parse won't work.

1 Answers

Your string is not valid JSON. You need to format your string similar to the following. Once you have valid JSON, you can parse it, modify it, and re-serialize it back into JSON data.

const content = `
{
  "host": { "name": "HOST", "address": "0.0.0.0" },
  "port": { "name": "PORT", "address": 1337 },
  "app": {
    "keys": ["APP_KEYS"]
  }
}
`;

const obj = JSON.parse(content); // Deserialize

obj.app.keys.push("APP_KEY_2"); // Modify

const json = JSON.stringify(obj, null, 2); // Serialize

console.log(json); // Print updated JSON
.as-console-wrapper { top: 0; max-height: 100% !important; }

You shouldn't import a script as plaintext. The string your provided could only be created by utilizing classes/objects as seen in this example below. This is not JSON, and should be avoided.

const content = `{ host: env("HOST", "0.0.0.0"), port: env.int("PORT", 1337), app: { keys: env.array("APP_KEYS"), },}`

class env {
  constructor(hostname, ipAddress) {
    this.hostname = hostname;
    this.ipAddress = ipAddress;
  }
  toString() {
    return `{ hostname: "${this.hostname}", ipAddress: ${this.ipAddress} }`;
  }
  toJSON() {
    return `env("${this.hostname}", "${this.ipAddress}")`;
  }
}

const host = new env("HOST", "0.0.0.0");
console.log(host.toString()); // { hostname: "HOST", ipAddress: 0.0.0.0 }
console.log(JSON.stringify(host)); // env("HOST", "0.0.0.0")

Related