简体   繁体   English

如何将js对象转换为js文字?

[英]how to convert js object to js literal?

I am using nodejs.我正在使用 nodejs。 I have an object.我有一个对象。

const objA = { key : 'value' };

the target is to generate a new file obja.js, with the same literals inside the file, not JSON literal.目标是生成一个新文件 obja.js,在文件中使用相同的文字,而不是 JSON 文字。 How can I achieve this?我怎样才能做到这一点? If I use如果我使用

let result = JSON.stringfy(objA);

result would be a JSON literal:结果将是一个 JSON 文字:

{ "key" : "value" }

But I want a js literals:但我想要一个 js 文字:

{ key : 'value' }

You can use util here, its also handy when you want to console.log any object你可以在这里使用 util,当你想要 console.log 任何对象时它也很方便

const objA = { keyword : 'value' };
const fs = require('fs');
const util = require('util')
const objA1 = util.inspect(objA, {showHidden: false, depth: null})
fs.writeFileSync('./obja.js', objA1 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM