How to create a JSON file from a JS?

Asked

Viewed 2,177 times

3

Hello, I created a simple page where the user can define some fields. I need to implement the following function: When you click the 'Create' button, the application should generate a JSON file with all the fields that have been created. As I know almost nothing of JSON wanted a help to know if it is possible to do this and if possible an orientation of how to do.

$(document).ready(function(){
    var num = 0

    $('#FieldCount').on('change', function() {
        $('#Home').empty()
        num = $(this).val() 
        $("#Home").append(`
            <br>
            <br>
            <div class="row changer" style="">
                <div class ='col-xs-3'>   
                    <label>Tipo</label>
                 </div>
                <div class ='col-xs-3'>   
                     <label>Nome</label>
                 </div>
                 <div class ='col-xs-6'>
                    <label>Campo</label>
                 </div>
            </div>
        `)
            
        for (var x = 0; x < num; x++) {
            $(`
            <div class="row" >
                <label id="Count" >${x+1}</label>
                <div class="col-xs-3">
                    <select name="${x}" class='fieldtype' style='border: none; outline: none; height: 20px;width: 100%;'>
                        <option>Input</option>
                        <option>Combo Box</option>
                    </select>
                </div>
                <div class="col-xs-3">
                    <input class="${x} in" type="text" value="Campo" style="border-radius: 3px; background-color: grey; border: none; outline: none;/>
                </div>
                <div class="col-xs-2" class="OpCom${x}">
                    <select style="display: none;border: none; height: 25px; border-radius: 3px;" name=${x} class="OpCom">
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                        <option>5</option>
                        <option>6</option>
                        <option>7</option>
                        <option>8</option>
                        <option>9</option>
                        <option>10</option>
                    </select>
                    <div class='morein' name=${x}>

                    </div>
                </div>
            </div>
            `).appendTo('#Home')
        }

        $('.fieldtype').on('change', function() {
            temp_index = $(this).attr('name')

            if($(this).val() == 'Input') {
                console.log('input')
                $(`.${temp_index}`).addClass('in')
                $(`.OpCom[name=${temp_index}]`).removeClass('Ready')
                $(`.OpCom[name=${temp_index}]`).css('background-color', 'rgba(0,0,0,0)')
                $(`.OpCom[name=${temp_index}]`).css('color', 'rgba(0,0,0,0)')
                $(`.OpCom${temp_index}`).hide()
                $(`.morein[name=${temp_index}]`).hide()
                
            } else {
                $(`.OpCom[name=${temp_index}]`).css('background-color', 'buttonface')
                $(`.OpCom[name=${temp_index}]`).css('color', 'black')
                    $(`.OpCom${temp_index}`).append(`
                    <select style="border: none; height: 25px; border-radius: 3px;" name=${temp_index} class="OpCom">
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                        <option>5</option>
                        <option>6</option>
                        <option>7</option>
                        <option>8</option>
                        <option>9</option>
                        <option>10</option>
                    </select>
                    `)
                
                console.log('combo')
                $(`.${temp_index}`).removeClass('in')
                $(`.${temp_index}`).addClass('on')
                console.log($(`.${temp_index}`).val())
                $(`.OpCom[name=${temp_index}]`).addClass('Ready')
                $(`.morein[name=${temp_index}]`).show()
                
                $(`.OpCom${temp_index}`).append(`
                <select style="border: none; height: 25px; border-radius: 3px;" name=${temp_index} class="OpCom">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                    <option>7</option>
                    <option>8</option>
                    <option>9</option>
                    <option>10</option>
                </select>
                `)
            }
            
            var a = $(this).attr('name')
            $(`.OpCom[name=${a}]`).show()


            $(`.OpCom[name=${a}]`).change(function() {
                $(`.morein[name=${a}]`).empty()
                for (var z = 0; z < $(`.OpCom[name=${a}]`).val(); z++) {
                    $(`.morein[name=${a}]`).append(`<input name='${a}i' type=text value="item" style="border: none; border-bottom: 1px solid black; broder-radius: 3px; background-color: grey;" />`)
                }
            })
        })
    })
});
<!DOCTYPE html>
<html>
<head>


<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</head>
<body style="background-color: #cccccc;">
    <div style="text-align: center;"class="container-fluid">
        <h2 style="text-align: center;">Gerador de App</h2>
        <h4 style="text-align: center;">Quantos campos deseja criar?</h4>
        <select id="FieldCount" style="width: 100px; border: none; width: 150px;height: 30px; border-radius: 3px; outline: none;">
            <option name="one">1</option>
            <option name="one">2</option>
            <option name="one">3</option>
            <option name="one">4</option>
            <option name="one">5</option>
            <option name="one">6</option>
            <option name="one">7</option>
            <option name="one">8</option>
            <option name="one">9</option>
            <option name="one">10</option>
        </select>
        <div id="Home">

        </div>
        
        <a href=""><button id="Create" style=" margin-top: 100px;bottom: 0; border: none; font-size: 25px; border-radius: 3px;">Criar</button></a>
    </div>
</body>
</html>

2 answers

3

You have to go through all the class in and class on input and save the values in a simple object by adding the item values with an array. An example of how it would be done would be the following

$(document).ready(function () {
  var num = 0

  $('#FieldCount').on('change', function () {
    $('#Home').empty()
    num = $(this).val()
    $("#Home").append(`
            <br>
            <br>
            <div class="row changer" style="">
                <div class ='col-xs-3'>   
                    <label>Tipo</label>
                 </div>
                <div class ='col-xs-3'>   
                     <label>Nome</label>
                 </div>
                 <div class ='col-xs-6'>
                    <label>Campo</label>
                 </div>
            </div>
        `)

    for (var x = 0; x < num; x++) {
      $(`
            <div class="row" >
                <label id="Count" >${x + 1}</label>
                <div class="col-xs-3">
                    <select name="${x}" class='fieldtype' style='border: none; outline: none; height: 20px;width: 100%;'>
                        <option>Input</option>
                        <option>Combo Box</option>
                    </select>
                </div>
                <div class="col-xs-3">
                    <input class="${x} in" type="text" value="Campo" style="border-radius: 3px; background-color: grey; border: none; outline: none;"/>
                </div>
                <div class="col-xs-2" class="OpCom${x}">
                    <select style="display: none;border: none; height: 25px; border-radius: 3px;" name=${x} class="OpCom">
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                        <option>5</option>
                        <option>6</option>
                        <option>7</option>
                        <option>8</option>
                        <option>9</option>
                        <option>10</option>
                    </select>
                    <div class='morein' name=${x}>

                    </div>
                </div>
            </div>
            `).appendTo('#Home')
    }

    $('.fieldtype').on('change', function () {
      temp_index = $(this).attr('name')

      if ($(this).val() == 'Input') {
        console.log('input')
        $(`.${temp_index}`).addClass('in')
        $(`.OpCom[name=${temp_index}]`).removeClass('Ready')
        $(`.OpCom[name=${temp_index}]`).css('background-color', 'rgba(0,0,0,0)')
        $(`.OpCom[name=${temp_index}]`).css('color', 'rgba(0,0,0,0)')
        $(`.OpCom${temp_index}`).hide()
        $(`.morein[name=${temp_index}]`).hide()

      } else {
        $(`.OpCom[name=${temp_index}]`).css('background-color', 'buttonface')
        $(`.OpCom[name=${temp_index}]`).css('color', 'black')
        $(`.OpCom${temp_index}`).append(`
                    <select style="border: none; height: 25px; border-radius: 3px;" name=${temp_index} class="OpCom">
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                        <option>5</option>
                        <option>6</option>
                        <option>7</option>
                        <option>8</option>
                        <option>9</option>
                        <option>10</option>
                    </select>
                    `)

        console.log('combo')
        $(`.${temp_index}`).removeClass('in')
        $(`.${temp_index}`).addClass('on')
        console.log($(`.${temp_index}`).val())
        $(`.OpCom[name=${temp_index}]`).addClass('Ready')
        $(`.morein[name=${temp_index}]`).show()

        $(`.OpCom${temp_index}`).append(`
                <select style="border: none; height: 25px; border-radius: 3px;" name=${temp_index} class="OpCom">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                    <option>7</option>
                    <option>8</option>
                    <option>9</option>
                    <option>10</option>
                </select>
                `)
      }

      var a = $(this).attr('name')
      $(`.OpCom[name=${a}]`).show()


      $(`.OpCom[name=${a}]`).change(function () {
        $(`.morein[name=${a}]`).empty()
        for (var z = 0; z < $(`.OpCom[name=${a}]`).val(); z++) {
          $(`.morein[name=${a}]`).append(`<input name='${a}i' type=text value="item" style="border: none; border-bottom: 1px solid black; broder-radius: 3px; background-color: grey;" />`)
        }
      })
    })
  })

  $('#Create').on('click', (event) => {
    event.preventDefault();
    const home = $('#Home')[0];
    let aux = { comboboxs: [], inputs: [] };

    aux.comboboxs = getSelects(home);
    aux.inputs = getInputs(home);
    console.log(aux);
  });
});

const getInputs = (home) =>  {
  const inputs = home.getElementsByClassName('in');
  const lengthInputs = inputs.length;
  const auxInputs = [];

  for(let i = 0; i < lengthInputs; i++) {
    auxInputs.push(inputs[i].value);
  }

  return auxInputs;
}

const getSelects = (home) => {
  // get OpCom selects
  const selects = home.getElementsByClassName('OpCom');
  const lengthSelects = selects.length;
  const auxSelects = [];
  let parent;
  let inputsSelect;
  let grandparent;
  let items;

  for (let i = 0; i < lengthSelects; i++) {
    // if select display is none continue
    if ($(selects[i]).css('display') === 'none') continue;

    items = [];
    // get div parent of Opcom
    parent = $(selects[i]).parent()[0];
    inputsSelect = parent.getElementsByClassName('morein')[0];
    //get inputs of moreIn
    inputsSelect = inputsSelect.getElementsByTagName('input');
    for (let j = 0; j < inputsSelect.length; j++) {
      items.push($(inputsSelect[j]).val());
    }

    // get grandparent div
    grandparent = $(parent).parent()[0];
    // add combobox
    auxSelects.push({
      // get value from input on
      name: grandparent.getElementsByClassName('on')[0].value,
      items: items
    });
  }

  return auxSelects;
}
<!DOCTYPE html>
<html>
<head>


<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</head>
<body style="background-color: #cccccc;">
    <div style="text-align: center;"class="container-fluid">
        <h2 style="text-align: center;">Gerador de App</h2>
        <h4 style="text-align: center;">Quantos campos deseja criar?</h4>
        <select id="FieldCount" style="width: 100px; border: none; width: 150px;height: 30px; border-radius: 3px; outline: none;">
            <option name="one">1</option>
            <option name="one">2</option>
            <option name="one">3</option>
            <option name="one">4</option>
            <option name="one">5</option>
            <option name="one">6</option>
            <option name="one">7</option>
            <option name="one">8</option>
            <option name="one">9</option>
            <option name="one">10</option>
        </select>
        <div id="Home">

        </div>
        
        <a href=""><button id="Create" style=" margin-top: 100px;bottom: 0; border: none; font-size: 25px; border-radius: 3px;">Criar</button></a>
    </div>
</body>
</html>

  • Very good what you did. Now I need to understand how to pass this to a JSON object. For example: For me to transform the auxInputs object to JSON I should do so: var myJSON = JSON.stringify(auxInputs);

  • When I do that error way (auxInputs is not defined).

  • The aux object in the Event 'click' of the create button is already a flat object (json), it does not need to pass this to JSON

  • I understood, but how could I take this object and put it inside a TXT file for me to access the information?

2

Hello, I know this answer is in 2020, but I still want to help For you to create a file ". json" or in any other format using JS you do so:

var fs = require('fs');
fs.appendFile('Meu-arquivo.txt'/*Aqui é o nome do arquivo*/, 'Olá mundo'/*Aqui é o conteudo do arquivo*/, function (err) {
  if (err) throw err;
  console.log('Arquivo Salvo!');
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.