Home > front end >  How can I convert a JSON object into javascript file with my own format
How can I convert a JSON object into javascript file with my own format

Time:11-12

I have a json object like this

{
   APP_NAME: "Test App",
   APP_TITLE: "Hello World"
}

Now I want to convert this into a javascript file and download that file the file format should be like this

// config.ts

export const APP_NAME: "Test App";
export const APP_TITLE: "Hello World";

CodePudding user response:

For this case, you can use fs.createWriteStream() to write the data into a file. Loop the json object and append the content.

Option 1: Backend-side

// Initialize the file
var fs = require('fs')
var editor = fs.createWriteStream('config.ts')

const data = {
    APP_NAME: "Test App",
    APP_TITLE: "Hello World"
};

// Loop every keys
Object.keys(data).forEach((key) => {
    // Append the text into the content
    editor.write(`export const ${key}: "${data[key]}";\n`)
});

// Save everything and create file
editor.end()

Option 2: Frontend-side

<html>
    <script>
        const data = {
            APP_NAME: "Test App",
            APP_TITLE: "Hello World"
        };

        let content = '';
        Object.keys(data).forEach((key) => {
            // Append the text into the content
            content  = `export const ${key}: "${data[key]}";\n`;
        });

        let a = document.createElement('a');
        a.href = "data:application/octet-stream," encodeURIComponent(content);
        a.download = 'config.ts';
        a.click();
    </script>
</html>
  • Related