0

I have a <select> with a list of country <option>s. I want to turn my list of country <option>s into a file with an array of objects so I can import the array, and loop through it.

What I have:

<option data-code="US" value="USA">United States</option>
<option data-code="AU" value="Australia">Australia</option>
<option data-code="CA" value="Canada">Canada</option>
<option data-code="GB" value="United Kingdom">United Kingdom</option>

What I would like:

countries.js    
var countriesList = [
      {
        "data-code": "US",
        "name": "United States",
        "value": "USA"
      },
    ]

I know this has to be possible with Node in the command line, or python, something similar, but I must not be searching the right keywords. Even pointing to a resource or providing key words would be appreciated.

Dan Byler
  • 15
  • 5

2 Answers2

1

Something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Countries Select</title>
</head>
<body>
    <select name="" id="">
        <option data-code="US" value="USA">United States</option>
        <option data-code="AU" value="Australia">Australia</option>
        <option data-code="CA" value="Canada">Canada</option>
        <option data-code="GB" value="United Kingdom">United Kingdom</option>
    </select>
</body>
<script>
    const DOMOptions = document.querySelectorAll('option')

    const countriesList = Array.from(DOMOptions).map( DOMOption => {
        const option = {}
        option['data-code'] = DOMOption.dataset.code
        option['name'] = DOMOption.text
        option['value'] = DOMOption.value
        return option
    })

    console.log(countriesList)
</script>
</html>

Now, a basic use of fs (Node.js):

const fs = require('fs')

const countriesList = [
    {
      "data-code": "US",
      "name": "United States",
      "value": "USA",
    }
]

// Now transform de array from Array to JSON string
const countriesJSON = JSON.stringify(countriesList)

//////// To write
try {
    console.log(countriesList)
    fs.writeFileSync('countries.json', countriesJSON) 
    // fs.writeFileSync('countries.txt', countriesList) // Or countries.txt if you want the file with txt extension
    //fs.appendFileSync('countries.txt', countriesList) // If you want to just append not overwrite
} catch(err){
    // Handle error
    console.log(err)
}

// /////// To read
const dataBuffer = fs.readFileSync('countries.json') // Returns a buffer, which is a way to node js to represent binary data, bytes
const dataJSON = dataBuffer.toString() // You maybe want to transform the bytes to string
console.log(dataJSON) // Print the string

const data = JSON.parse(dataJSON) // Or maybe want to transform the string to array again
console.log(data)
Andrés Muñoz
  • 559
  • 3
  • 8
0

I was researching the Node fs package when Andres provided a great starting point to do it in the browser. These two similar StackOverflow answers (1,2) prompted me to:

I am still curious to figure out how to use the Node fs package, but many thanks to Andres for starting me in the right direction.

const DOMOptions = document.querySelectorAll('#country-select option');
const downloadBtn = document.getElementById("link-download");
const option = {};
let textFileURL = null;

const countriesList = Array.from(DOMOptions).map(DOMOption => {
  option['data-code'] = DOMOption.dataset.code
  option['name'] = DOMOption.text
  option['value'] = DOMOption.value

  return option;
})

const makeTextFile = (text) => {
  var data = new Blob([JSON.stringify(text, null, 2)], {
    type: 'application/json'
  });

  // If we are replacing a previously generated file we need to
  // manually revoke the object URL to avoid memory leaks.
  if (textFileURL !== null) {
    window.URL.revokeObjectURL(textFileURL);
  }
  // creates a URL you can use as a href or src
  textFileURL = window.URL.createObjectURL(data);


  downloadBtn.href = `${textFileURL}`;
  //HTML5 "download" attribute enables download
  downloadBtn.download = 'countries.json';
  return option;
};

makeTextFile(countriesList)
<a id="link-download">download countries</a>
<select id="country-select">
  <option diabled value="">Select a Country</option>
  <option data-code="US" value="USA">United States</option>
  <option data-code="AU" value="Australia">Australia</option>
  <option data-code="CA" value="Canada">Canada</option>
  <option data-code="GB" value="United Kingdom">United Kingdom</option>
</select>
Dan Byler
  • 15
  • 5