Farhan
Farhan

Reputation: 2575

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:

[
    {
        "Player": "John",
        "TotalRuns": 4350,
        "AllRounder": false
    },
    {
        "Player": "Michael",
        "TotalRuns": 8373,
        "AllRounder": true
    }
]

Formatting of JSON is not important.

Using jQuery etc. is not an option. I am thinking to convert the list into array and then calling JSON.stringify. But I not sure if that will work because there can be many items in the list.

Upvotes: 0

Views: 168

Answers (3)

iBagus
iBagus

Reputation: 11

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)

Upvotes: 1

Charlie
Charlie

Reputation: 23778

Get the children of the ol, iterate them and construct the array.

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>

Upvotes: 0

Andy
Andy

Reputation: 525

Here you 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.

Upvotes: 0

Related Questions