As in this question, I want to write a large javascript object as an object literal, not as a string, so I can avoid having to use JSON.parse later. Is there a convenient way to render my object like this:
const myObject = { "someKey": "someValue" };
instead of like this?
const myString = "{ \"someKey\":\"someValue\" }";
const myObject = JSON.parse(myString);
Edit: Sorry, I wasn't clear the first time. I want to write Javascript code to print the object literal to a file. If I use JSON.stringify, I get a string, not a literal.
What I want is something like this function:
function writeObjectLiteral(objectToWrite) {
const objectAsLiteralString = _.map(objectToWrite, (value, key) => {
if (Array.isArray(value)) {
return `${key}:[${value.join(',')}]`;
}
if (typeof value === 'object') {
return `${key}:${writeObjectLiteral(value)}`;
} else {
return `${key}:${value}`;
}
}).join(',');
return `{${objectAsLiteralString}}`;
}
const testObject = {
something: "whatever",
array: [
'something',
'other thing'
],
nestedObj: {
something: "whatever",
array: [
'something',
'other thing'
]
}
};
fs.writeFileSync(
'outputFile',
'const myObject = ' + writeObjectLiteral(testObject) + ';', 'utf8'
);