[英]How to convert list to JSON in JavaScript?
I have a list like this:我有一个这样的列表:
<ol class="CricketPlayers">
<li id="1">Player: John, TotalRuns: 4350, AllRounder: false</li>
<li id="2">Player: Michael, TotalRuns: 8373, AllRounder: true</li>
</ol>
I need to convert this into JSON like this:我需要将其转换为 JSON ,如下所示:
[
{
"Player": "John",
"TotalRuns": 4350,
"AllRounder": false
},
{
"Player": "Michael",
"TotalRuns": 8373,
"AllRounder": true
}
]
Formatting of JSON is not important. JSON 的格式并不重要。
Using jQuery etc. is not an option.不能使用 jQuery 等。 I am thinking to convert the list into array and then calling
JSON.stringify
.我正在考虑将列表转换为数组,然后调用
JSON.stringify
。 But I not sure if that will work because there can be many items in the list.但我不确定这是否可行,因为列表中可能有很多项目。
try this:尝试这个:
let result = [];
let parent = document.querySelector(".CricketPlayers").children;
Array.prototype.forEach.call(parent, child => {
let x = child.innerHTML.split(",");
let y = JSON.stringify(x).replace("[","{").replace("]","}");
result.push(y)
});
console.log(result)
Here you go:这里是 go:
[...document.querySelectorAll('.CricketPlayers li')]
.map(node => node.innerText.match(/Player\: (\w+). TotalRuns\: (.*). AllRounder\: (.*)/))
.map(matchedParts => ({ Player: matchedParts ? matchedParts[1] : '', TotalRuns: matchedParts ? matchedParts[2] : 0, AllRounder: matchedParts ? matchedParts[3] : 0 }))
and the results are like yours.结果和你的一样。
Get the children of the ol
, iterate them and construct the array.获取
ol
的孩子,迭代它们并构造数组。
let ol = document.getElementsByClassName('CricketPlayers'); let output =[...ol[0].children].map(item => { let props = item.innerHTML.split(','); return props.reduce((a, c) => { aProp = c.split(':'); a[aProp[0].trim()] = aProp[1].trim(); return a }, {}) }) console.log(output)
<ol class="CricketPlayers"> <li id="1">Player: John, TotalRuns: 4350, AllRounder: false</li> <li id="2">Player: Michael, TotalRuns: 8373, AllRounder: true</li> </ol>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.