简体   繁体   中英

Convert Javascript Object into JSON String

I have a Javascript object that I need to convert into JSON. The object is in a .js file. I need to read the .js file and convert the object to JSON. I'm trying to do this with NodeJS. Here's the object in the .js file:

module.exports = [
  'example1',
  'test1',
  'example2',
  'tester3'
];

Here's the code that I'm using to read the file:

var fs = require('fs');
var content;
fs.readFile('/someotherpath/somewhereelse/myfile.js'), function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;

    processFile();
});

function processFile() {
    console.log(content);
}

My results are:

<Buffer 2f 2f 2f 4c 69 73 74 20 77 65 62 68 6f 6f 6b 20 70 61 74 68 73 20 74 68 61 74 20 73 68 6f 75 6c 64 20 62 65 20 70 72 6f 78 69 65 64 0a 2f 2f 20 74 6f ... >

How do I convert the real contents of the file, the object, to a JSON string?

Just use require :

 var data = require('/someotherpath/somewhereelse/myfile.js');
 var jsonString = JSON.stringify(data);

You can use Javascripts require function to load the js file. Then use the Javascript built in module for stringifing Json objects.

Here is an example.

var mod = require('./mod');

console.log(JSON.stringify(mod));

From Mozilla Developer Network, MDN "The JSON.stringify() method converts a JavaScript value to a JSON string..."

Check out MDN if you would like to read more about stringify(), it's description, and it's parameters.

If no encoding is specified, then the raw buffer is returned , so you should use

fs.readFile('/someotherpath/somewhereelse/myfile.js','utf8', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;

    processFile();
});

or you could simply convert to string data.toString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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