[英]create a json from array of string using javascript
After scraping an html table I have stored my data in the variable:抓取 html 表后,我将数据存储在变量中:
var data = ["header1", "header2", "a1", "a2", "b1", "b2", "c1", "c2"];
I want to create a json file in the form:我想以以下形式创建一个json文件:
var json = [
{
"header1":"a1",
"header2":"a2"
},
{
"header1":"b1",
"header2":"b2"
},
{
"header1":"c1",
"header2":"c2"
}
];
I know that I need我知道我需要
var headers={};
and load it with并加载它
headers["header1"] and headers["header2"]标头["header1"] 和标头["header2"]
I also need我也需要
var jsonObj = [];
and push the array headers inside jsonObj:并将数组头推入 jsonObj:
jsonObj.push(headers);
Is it possible to create it?是否可以创建它?
I'll make some assumptions, and then attempt to answer your question.我会做一些假设,然后尝试回答您的问题。
To me, it seems your table looks something like:对我来说,你的桌子看起来像:
header1![]() |
header2![]() |
---|---|
a1 ![]() |
a2 ![]() |
b1 ![]() |
b2 ![]() |
c1 ![]() |
c2 ![]() |
Simply starting with the array you already have, we can then just pick out two and two values at the time.只需从您已有的数组开始,然后我们就可以同时挑选出两个和两个值。 See the code below
看下面的代码
const COLUMN_COUNT = 2 const data = ["header1", "header2", "a1", "a2", "b1", "b2", "c1", "c2"] // this removes the headers from the data-list, // and stores them in the headers variable const headers = data.splice(0, COLUMN_COUNT) const output = [] while(data.length > 0) { const row = {} const values = data.splice(0, COLUMN_COUNT) for(const [idx, value] of values.entries()) { const header = headers[idx] row[header] = value } output.push(row) } console.log(output)
There is actually no relation between header and the values, but assuming the first two elements are always header1 and header2
and the next 1 pair will be the value of header1 and header2 respectively, this might do it header 和值之间实际上没有关系,但假设前两个元素始终是
header1 and header2
,接下来的一对将分别是 header1 和 header2 的值,这可能会做到
const data = ["header1", "header2", "a1", "a2", "b1", "b2", "c1", "c2"]; const res = []; const h1 = data[0]; const h2 = data[1]; data.splice(0, 2); for (let i = 0; i < data.length; i++) { if (i % 2 != 0) { const payload = {}; payload[h1] = data[i - 1]; payload[h2] = data[i]; res.push(payload); } } console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.