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);
        }
5
  • 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? Commented Jun 22, 2021 at 15:48
  • data is already an object do not parse it (or stringify it) Commented Jun 22, 2021 at 15:48
  • no need for parsing if it's already an object Commented Jun 22, 2021 at 15:49
  • What you are parsing is an object, not an array. Should be for(var i in data); Commented Jun 22, 2021 at 15:49
  • Not entirely a duplicate, but this should have been the first place you looked, giving: SyntaxError: Unexpected token o in JSON at position 1 Commented Jun 22, 2021 at 15:58

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

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 => $('<div>', {class: "name", text: arr[1].name}).appendTo("#datalist").wrap('<div class="item">'));
@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?
Hm... if you do <div class="item"><div class="name">${arr[1].name}</div></div> and arr[1].name is not HTML, but plain text, then no, it would not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.