简体   繁体   English

如何基于 dom 节点列表创建包含 json 对象数组的文件

[英]How to create a file with an array of json objects based on a list of dom nodes

I have a <select> with a list of country <option> s.我有一个<select>和一个国家列表<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.我想将我的 country <option>列表转换为一个包含对象数组的文件,这样我就可以导入该数组并循环遍历它。

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.我知道这必须通过命令行中的 Node 或 python 来实现,类似的东西,但我不能搜索正确的关键字。 Even pointing to a resource or providing key words would be appreciated.即使指向资源或提供关键词也将不胜感激。

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):现在, 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)

I was researching the Node fs package whenAndres provided a great starting point to do it in the browser.我正在研究 Node fs package,当时Andres提供了一个很好的起点,可以在浏览器中进行。 These two similar StackOverflow answers ( 1 , 2 ) prompted me to:这两个相似的 StackOverflow 答案( 12 )提示我:

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.我仍然很想知道如何使用 Node fs package,但非常感谢 Andres 让我朝着正确的方向前进。

 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>

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

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