0

I get this as my ajax request result:

{
   "12":{
      "name":"Diana",
      "age":"51",
      "mid":"562132",
      "character":{
         "height":"180",
         "suffix":" cm",
         "prefix":"Heinght in: ",
         "ratio":{
            "w":"99",
            "l":"12"
         }
      }
   },
   "13":{
      "name":"Rachel",
      "age":"32",
      "mid":"56547",
      "character":{
         "height":"1.7",
         "suffix":" m",
         "prefix":"Height in: ",
         "ratio":{
            "w":"45",
            "l":"1"
         }
      }
   },
   "14":{
      "name":"Nova",
      "age":"34",
      "mid":"554666",
      "character":{
         "price":"11.999",
         "suffix":" EUR",
         "prefix":"Height in: ",
         "ratio":{
            "w":"176",
            "l":"87"
         }
      }
   }
}

I want to loop through and build html for each item, this was my attempt; I tryed json parse and json stringify but I get undefined error or Uncaught SyntaxError: Unexpected token o in JSON at position 1:

        function createHtml(data){
var data = JSON.parse(data);
            var html = '<h1>Data:</h1>';
            
            for(var i = 0; i < data.length; i++) {
                html += '<div class="item">';
                html += '<div class="name">'+data[i].name+'</div>';
                html += '</div>';
            }
            $('#datalist').html(html);
        }
mheonyae
  • 581
  • 2
  • 8
  • 24
  • No repro on: `Uncaught SyntaxError: Unexpected token o in JSON at position 1` - parses okay to me, are you sure that that's the data you're passing to the function and it's being passed as a string? – Nick is tired Jun 22 '21 at 15:48
  • data is already an object do not parse it (or stringify it) – Musa Jun 22 '21 at 15:48
  • no need for parsing if it's already an object – Roljhon Jun 22 '21 at 15:49
  • What you are parsing is an object, not an array. Should be [`for(var i in data);`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...in) – Peter Krebs Jun 22 '21 at 15:49
  • Not entirely a duplicate, but [this](https://stackoverflow.com/search?q=Unexpected+token+o+in+JSON) should have been the first place you looked, giving: [SyntaxError: Unexpected token o in JSON at position 1](https://stackoverflow.com/a/38380728/2181514) – freedomn-m Jun 22 '21 at 15:58

1 Answers1

1

The error you see is because you're calling JSON.parse() on an object, not a string. The JSON string has already been deserialised, so you don't need to perform that action again.

The second issue you have is that your data structure is an object. To loop through that you need a method of converting it to an array. This can be achieved using Object.entries().

From there you can simply use map() to build your HTML strings based on the content of the objects in the array. Try this:

function createHtml(data) {
  let html = data.map(arr => `<div class="item"><div class="name">${arr[1].name}</div></div>`).join('');
  $('#datalist').html(`<h1>Data:</h1>${html}`);
}

let data = {12:{name:"Diana",age:"51",mid:"562132",character:{height:"180",suffix:" cm",prefix:"Heinght in: ",ratio:{w:"99",l:"12"}}},13:{name:"Rachel",age:"32",mid:"56547",character:{height:"1.7",suffix:" m",prefix:"Height in: ",ratio:{w:"45",l:"1"}}},14:{name:"Nova",age:"34",mid:"554666",character:{price:"11.999",suffix:" EUR",prefix:"Height in: ",ratio:{w:"176",l:"87"}}}};
createHtml(Object.entries(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="datalist"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Since the OP indicates that they are using jQuery, and bare-bones JS string interpolation does not do proper HTML escaping, I'd suggest something like `data.forEach(arr => $('
    ', {class: "name", text: arr[1].name}).appendTo("#datalist").wrap('
    '));`
    – Tomalak Jun 22 '21 at 16:06
  • @Tomalak what benefit would that have over using the `html()` method to add the entire array of strings? The HTML would be escaped/sanitised at that stage, would it not? – Rory McCrossan Jun 22 '21 at 16:40
  • Hm... if you do `
    ${arr[1].name}
    ` and `arr[1].name` is not HTML, but plain text, then no, it would not.
    – Tomalak Jun 22 '21 at 16:42