如何将数组组转换为 Json?
Posted
技术标签:
【中文标题】如何将数组组转换为 Json?【英文标题】:How to convert group of array into Json? 【发布时间】:2021-01-16 02:26:15 【问题描述】:我有多个 <div>
元素,它们有 3 个共同点(<h3>
、<textarea>
、<img>
)。单击按钮后,我需要获得 JSON 结果(在下面共享)。
这是我尝试过的,但我无法转换为 JSON,但我能够将其转换为单独的数组。
function get_json()
var groups = Array.from(document.querySelectorAll(".StackedList"));
var imgs = groups.map(function(group)
return Array.from(group.querySelectorAll("img")).map(function(item)
return new URL(item.src).pathname.substring(1);
);
);
var desc = groups.map(function(group)
return Array.from(group.querySelectorAll("textarea")).map(function(item)
return item.value
);
);
var h3text = groups.map(function(group)
return Array.from(group.querySelectorAll("h3")).map(function(item)
return item.innerText
);
);
alert(imgs + desc + h3text)
return imgs, desc, h3text
<div class="StackedList" id="group1">
<h3 id="c1" style="display:inline" contenteditable="true">Item 1</h3>
<textarea id="desc1" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/10.jpg" />
<img class="draggable" src="http://localhost:99/11.jpg" />
<img class="draggable" src="http://localhost:99/12.jpg" />
</div>
<div class="StackedList" id="group2">
<h3 id="c2" style="display:inline" contenteditable="true">Item 2</h3>
<textarea id="desc2" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/8.jpg" />
<img class="draggable" src="http://localhost:99/7.jpg" />
<img class="draggable" src="http://localhost:99/2.jpg" />
</div>
<div class="StackedList" id="group3">
<h3 id="c3" style="display:inline" contenteditable="true">Item 3</h3>
<textarea id="desc3" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/1.jpg" />
</div>
<input type="button" value="Get json" onclick="get_json()">
预期输出
我需要在单击按钮时获取 JSON。
"Item 1":
"descrption": "Entered text value",
"images": ["10.jpg", "11.jpg", "12.jpg"]
,
"Item 2":
"descrption": "Entered text value",
"images": ["8.jpg", "7.jpg", "2.jpg"]
,
"Item 3":
"descrption": "Entered text value",
"images": ["1.jpg"]
【问题讨论】:
什么是Item 1
第1项
h3元素文本 【参考方案1】:这将是一个快速的解决方案:
它正在创建一个名为json
的新对象。
代码遍历您的 h3text
数组。对于每个条目,都会创建一个新对象 (newEntry
),以便您的 json
对象成为嵌套对象。
在newEntry
对象中,创建了两个键description
(字符串)和ìmages
(数组)。之后,我检查一个键(例如"item 1"
是否已存在于json
中。如果不存在,则创建一个名为h3text[i]
的新键。
对于测试,您可以使用console.log(json)
来检查它是否符合您的需求。
注意:我不检查desc[i][0]
和imgs[i]
是否存在。因此,对于正确的循环,您应该检查它们是否不是undefined
。
let json = ;
for(let i = 0; i < h3text.length; i++)
let newEntry =
"description": desc[i][0],
"images": imgs[i]
// Only save ""item1" when there is no key with "item1" already
if(!json.hasOwnProperty(h3text[i]))
json[h3text[i]] = newEntry;
function get_json()
var groups = Array.from(document.querySelectorAll(".StackedList"));
var imgs = groups.map(function (group)
return Array.from(group.querySelectorAll("img")).map(function (item)
return new URL(item.src).pathname.substring(1);
);
);
var desc = groups.map(function (group)
return Array.from(group.querySelectorAll("textarea")).map(function (item)
return item.value
);
);
var h3text = groups.map(function (group)
return Array.from(group.querySelectorAll("h3")).map(function (item)
return item.innerText
);
);
let json = ;
for(let i = 0; i < h3text.length; i++)
let newEntry =
"description": desc[i][0],
"images": imgs[i]
// Only save ""item1" when there is no key with "item1" already
if(!json.hasOwnProperty(h3text[i]))
json[h3text[i]] = newEntry;
console.log(json)
return json
<div class="StackedList" id="group1">
<h3 id="c1" style="display:inline" contenteditable="true">Item 1</h3>
<textarea id="desc1" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/10.jpg" />
<img class="draggable" src="http://localhost:99/11.jpg" />
<img class="draggable" src="http://localhost:99/12.jpg" />
</div>
<div class="StackedList" id="group2">
<h3 id="c2" style="display:inline" contenteditable="true">Item 2</h3>
<textarea id="desc2" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/8.jpg" />
<img class="draggable" src="http://localhost:99/7.jpg" />
<img class="draggable" src="http://localhost:99/2.jpg" />
</div>
<div class="StackedList" id="group3">
<h3 id="c3" style="display:inline" contenteditable="true">Item 3</h3>
<textarea id="desc3" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/1.jpg" />
</div>
<input type="button" value="Get json" onclick="get_json()">
【讨论】:
感谢您的帮助!【参考方案2】:您正在将值抓取到数组中,但必须将其转换为 JSON object
。
您可以使用以下.reduce
和.map
函数来简化此操作
function get_json()
const groups = Array.from(document.querySelectorAll(".StackedList"));
const result = groups.reduce((res,obj)=>
const name = obj.querySelector('h3').textContent
res[name] =
descrption: obj.querySelector('textarea').value,
images: Array.from(obj.querySelectorAll('img')).map(item=>new URL(item.src).pathname.substring(1))
;
return res;
,);
console.log(result)
return result;
<div class="StackedList" id="group1">
<h3 id="c1" style="display:inline" contenteditable="true">Item 1</h3>
<textarea id="desc1" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/10.jpg" />
<img class="draggable" src="http://localhost:99/11.jpg" />
<img class="draggable" src="http://localhost:99/12.jpg" />
</div>
<div class="StackedList" id="group2">
<h3 id="c2" style="display:inline" contenteditable="true">Item 2</h3>
<textarea id="desc2" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/8.jpg" />
<img class="draggable" src="http://localhost:99/7.jpg" />
<img class="draggable" src="http://localhost:99/2.jpg" />
</div>
<div class="StackedList" id="group3">
<h3 id="c3" style="display:inline" contenteditable="true">Item 3</h3>
<textarea id="desc3" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/1.jpg" />
</div>
<input type="button" value="Get json" onclick="get_json()">
【讨论】:
感谢您的帮助【参考方案3】:您可以查询减速器中的元素。从 URL 中获取文件名相当简单。只需抓取 URL 对象的路径并找到最后一部分。
注意:看起来您来自 python 背景(使用蛇形大小写),即get_json
,但 javascript 约定使用类似 C 的变量/类驼峰形大小写,例如getJson
或 getJSON
。至于您的 html,属性通常是 kebab-case,例如class="stacked-list"
.
const grabFilename = (url) =>
(pathname =>
(index => -1 !== index
? pathname.substring(index + 1)
: pathname)
(pathname.lastIndexOf('/'))
)(new URL(url).pathname);
function getJson()
const json = [...document.querySelectorAll('.StackedList')].reduce((res, group) =>
return
...res,
[group.querySelector('h3').textContent]:
description: group.querySelector('textarea').value,
images: [...group.querySelectorAll('img')].map(img =>
return grabFilename(img.getAttribute('src'))
)
, );
console.log(json);
<div class="StackedList" id="group1">
<h3 id="c1" style="display:inline" contenteditable="true">Item 1</h3>
<textarea id="desc1" placeholder="Enter the description" name="w3review">Entered text value</textarea>
<img class="draggable" src="http://localhost:99/10.jpg" />
<img class="draggable" src="http://localhost:99/11.jpg" />
<img class="draggable" src="http://localhost:99/12.jpg" />
</div>
<div class="StackedList" id="group2">
<h3 id="c2" style="display:inline" contenteditable="true">Item 2</h3>
<textarea id="desc2" placeholder="Enter the description" name="w3review">Entered text value</textarea>
<img class="draggable" src="http://localhost:99/8.jpg" />
<img class="draggable" src="http://localhost:99/7.jpg" />
<img class="draggable" src="http://localhost:99/2.jpg" />
</div>
<div class="StackedList" id="group3">
<h3 id="c3" style="display:inline" contenteditable="true">Item 3</h3>
<textarea id="desc3" placeholder="Enter the description" name="w3review">Entered text value</textarea>
<img class="draggable" src="http://localhost:99/1.jpg" />
</div>
<input type="button" value="Get json" onclick="getJson()">
【讨论】:
感谢您的帮助【参考方案4】:您可以将 HTML 转换为 json,首先获取 DOM 元素,解析它们,然后在结果对象上使用 JSON.stringify。喜欢这里:Map HTML to JSON
【讨论】:
【参考方案5】:所有答案都很好。这是另一个。但选择权在你!
function get_json()
var groups = document.querySelectorAll(".StackedList");
//create a main object to store all the div objects
var listObj =
items: []
;
groups.forEach(item =>
//get images
var allimages = Array.from(document.querySelectorAll('#' + item.id + ' > img'));
//div object
var listItem =
//get title
title: document.querySelector('#' + item.id + ' > h3').innerHTML,
//get description
desc: document.querySelector('#' + item.id + ' > textarea').value,
//get image name with extension
images: allimages.map(item =>
return item.src.replace(/http:.*?\d\//, '');
)
//push the newly created object to main object's items array
listObj.items.push(listItem);
);
//output the data
alert(JSON.stringify(listObj));
【讨论】:
以上是关于如何将数组组转换为 Json?的主要内容,如果未能解决你的问题,请参考以下文章