JSON data to HTML "Element"

Hello everyone, I have a lot of JSON data. Now,I want to print them to HTML. Can anyone please help me do this.

I tried with ““document.getElementbyId””

<html>
<head>
  <title>hi</title>
</head>
<body>
<h2>Convert a string written in JSON format, into a JavaScript object.</h2>

<p id="output"></p>
<div id="a1"></p>

<script>
var obj = [{
    "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
    "type": "message",
    "text": "hey there",
    "source_team": "TN4AF0V5W",
    "team": "TN4AF0V5W",
    "user_profile": {
      "real_name": "marvelmohinish99",
      "team": "TN4AF0V5W"
    }
  },
  {
    "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
    "type": "message",
    "text": "welcome",
    "source_team": "TN4AF0V5W",
    "team": "TN4AF0V5W",
    "user_profile": {
      "real_name": "marvelmohinish99",
      "team": "TN4AF0V5W"
    }
  },
  {
    "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
    "type": "message",
    "text": "Help me",
    "source_team": "TN4AF0V5W",
    "team": "TN4AF0V5W",
    "user_profile": {
      "real_name": "marvelmohinish99",
      "team": "TN4AF0V5W"
    }
  }
];
for (i=0;i<=obj.length;i++) {

  var type = obj[i].type;

  var text = obj[i].text;

  var source_team = obj[i].source_team;

  var user_profile = obj[i].user_profile;

  var real_name = user_profile.real_name;

  console.log(text);
  console.log(real_name);


  
  document.getElementById("a1").innerHTML= text;

}





</script>
</body>
</html>

I’m not sure what exactly you’re trying to do. What do you want your output to look like?

One thing I can tell you that might help is that right now, with this code, you’re changing innerHTML of your ‘a1’ element with every iteration, so only the last iteration has effect. If you want to print our every value of the “text” property, you have to concatenate. For example, if you put the following code at the end of your for loop:

document.getElementById("a1").innerHTML += text + "<br>";

you’ll get this result:

hey there
welcome
Help me

I’m not sure if this is what you want, but I hope you at least get some idea of what you need to fix. Good luck! :smiley:

1 Like

Thanks for the reply. But I couldn’t get that output as you said.

The output you showed me is what i need exactly

Please help me with the code.I really need it

Have you copied the line I gave you instead of your last line in the for loop? Because it worked for me :confused:

Sorry, I got it:smiley::smiley::smiley:

Now,I want real_name and then text like:-

marvelmohinish99
hey there

marvelmohinish99
welcome

marvelmohinish99
help me

Actually I am playing it using class instead of ID .Now,I changed it’s perfect as you showed.

1 Like