Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
How to display json using pre tag in angularjs

How to display formatted json string inside dynamically created Div using forEach loop.

My code -

    <div id="container_div">
    </div>
        
     $scope.getJSON=()=>{
      var settings = {
      "url": "https://api/json,
      "method": "GET",
      "timeout": 0,
       };
        
       $.ajax(settings).done(function (response) {
       var container = document.getElementById("container_div");
       container.innerHTML="";
       var content="";
       response.jsonData.forEach((data)=>{
       var json = JSON.parse(data.json);
       var formatted = JSON.stringify(json).split(",").join("<br/>");
       var removeSlash = formatted.split("/").join('replace');
       content += `<div class="col-md-12 shadow p-3 mb-5 bg-white" style="max-height: 500px; overflow-x: auto; overflow-y: auto">
<p>${JSON.stringify(removeSlash)}</p> </div>`;
      container.innerHTML += content;
      });
      $scope.$apply();
       }).fail(function (error){
           console.log(error);
       });
       }
      }

The only problem I am facing currently is- I am getting "/" in the final output div like-

"{\"dob\":\"2021-03-17T19:32:24.163Z\"
\"codes\":[]
\"name\":\"Rahul\"}
{\"codes\":[]
\"type\":{\"codes\":[]}
\"name\":\"Rahul\"}]   
\"someDate\":\"2021-03-17T19:42:56.934Z\"}"

I have tried removing the slash using split and join but that's not working. How can I resolve this

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First of all, you should be parsing the response from the server most likely, rather than iterating the response and parsing individual elements.

Secondly, you say you're getting a "/" in your output, but I only see "\" - which is what JSON.stringify will do to escape quotes in a JSON string.

But the real call for help here is the way you're manipulating the DOM. In angularJS, you don't search the DOM for elements and add innerHTML. You use the built-in angular methods. Here is an example

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', '$http', function($scope, $http) {
    $http({
      method: "get",
      url: "https://jsonplaceholder.typicode.com/todos"
    }).then(function(response) {
      $scope.todos = response.data;
    })
  }]);
li {
  color: #666;
}

.completed {
  color: green;
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="todo in todos" ng-class="{'completed':todo.completed}">{{todo.title}}</li>
  </ul>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You don't need JSON.stringify in template string

let s = "{\"dob\":\"2021-03-17T19:32:24.163Z,\"codes\":[],\"name\":\"Rahul\"},{\"codes\":[],\"type\":{\"codes\":[]},\"name\":\"Rahul\"}],\"someDate\":\"2021-03-17T19:42:56.934Z\"}";
s = s.replace(/,/g, "<br/>");
document.querySelector('body').innerHTML = `<div class="col-md-12 shadow p-3 mb-5 bg-white" style="max-height: 500px; overflow-x: auto; overflow-y: auto">
<p>${s}</p> </div>`;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda