1
I’m running some tests with a file .json
with the intention of implementing the code in my application (if I succeed in the tests). I am using the following json file.
Follows the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="">
<title>Testando</title>
<style>
body {
margin: 0px;
padding: 0px;
background-color: #ccc;
}
div {
width: 40%;
height: 200px;
margin: auto;
border: 1px solid #000;
margin-top: 50px;
background-color: #fff;
border-radius: 5px;
}
</style>
</head>
<body>
<div>
</div>
<script>
var div = document.querySelector('div');
var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var obras = request.response;
procuraObra(obras);
}
function procuraObra(jsonObj){
var nomeObras = jsonObj['members']['name'];
for (var i = 0; i < nomeObras.length; i++){
if (nomeObras[i] == 'Madame Uppercut'){
var resultado = nomeObras[i];
}
}
if (resultado != null){
var primeiroP = document.createElement('p');
primeiroP.textContent = resultado;
}
div.appendChild(primeiroP);
}
</script>
</body>
</html>
Explaining from the functions:
function procuraObra(jsonObj){
var nomeObras = jsonObj['members']['name'];
In the above section I want to save the amount of names, which according to the file I am using are 3. In the section below I want to keep the name Madame Uppercut (it exists in the archive).
for (var i = 0; i < nomeObras.length; i++){
if (nomeObras[i] == 'Madame Uppercut'){
var resultado = nomeObras[i];
}
}
After having found and saved the name, in the code below I create the tag <p>
and add the name found on it (result variable):
if (resultado != null){
var primeiroP = document.createElement('p');
primeiroP.textContent = resultado;
}
And finally I add in div
to tag <p>
containing the name:
div.appendChild(primeiroP);
It was exactly what I needed, now I will work with the parse to abstract to the maximum this structure. worth!
– Lucas Inácio