View data from a Json file in HTML

Asked

Viewed 11,323 times

0

I’m stuck in a situation where I can’t turn the data blocks of the JSON file into HTML, nothing appears. Below I will put the codes for you to take a look

NOTE: If you can refer me to a legal JSON site I also need to know about filtering and adding posts, because each JSON block is a.

UPDATE OF THE PROBLEM

Guys I did below the updates of the resolution I had to show the JSON content in HTML, now just need to make the filter that has to be from data as popularity, Date and comment, I will follow the help of the friend and if I can do one more update here!!

HTML code (UPDATE)

<!DOCTYPE html>
<html lang="pt-br">
<head>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script type="text/javascript" src="dados.json"> </script>
</head>
<body>
    <header><input id="filtro" type="text" placeholder="Busca Rápida"></header>
    <main id= "dados" ></main>
    <footer></footer>
</body>
</html>

JAVASCRIPT FILTER CODE (working)

<script>
$('#filtro').keyup(function () {
    var yourtext = $(this).val();
    if (yourtext.length > 0) {
        var abc = $("section").filter(function () {
            var str = $(this).text();
            var re = new RegExp(yourtext, "i");
            var result = re.test(str);
            if (!result) {
                return $(this);
            }
        }).hide();
    } else {
        $("section").show();
    }
});
</script>

JSON(UPDATE)

window.onload=function(){
data = { person: [ 
    { 
    author: 'Nobtaka Nukui',
    title: 'Want people to use your product? Use it yourself',
    url: 'http://www.medium.com',
    category: 'Product Design',
    comments: '4 coments',
    created_at: '43 minutos atrás',
    classcor: 'corUm',
    foto: '<img src="img/ft-3.jpg" width="18" height="18" alt="Personagem1">',
    upvotes: 11 },
  {
    author: "Danil Ishutin",
    title: "Font Size Idea: px at Root, rem for Components, em for Text Elements",
    url: "http://www.css-tricks.com",
    category: "UX Theory",
    comments: '7 coments',
    created_at: '5 minutos atrás',
    classcor: 'corDois',
    foto: '<img src="img/ft-2.jpg" width="18" height="18" alt="Personagem2">',
    upvotes: 9},
    {
    author: "Kenny Schrub",
    title: "Some things cant be prototyped",
    url: "http://www.mika.el",
    category: "Opinion",
    comments:'25 coments',
    created_at: '7 minutos atrás',
    classcor: 'corTres',
    foto: '<img src="img/ft-2.jpg" width="18" height="18" alt="Personagem2">',
    isOwner: true,
    upvotes: 4  
        },
    {
    author: "Jacky Mao",
    title: "How to prototype without any tools",
    url: "http://www.jackymao.wix",
    category: "Opinion",
    comments: '0 coments',
    classcor: 'corTres',
    foto: '<img src="img/ft-1.jpg" width="18" height="18" alt="Personagem2">',
    upvotes: 4
        },

    {
    author: "Christopher Alesund",
    title: "Case study: Redesigning the Folyo landing page",
    url: "http://www.medium.com",
    category: "Case Study",
    comments: '0 coments',
    classcor: 'corQuatro',
    foto: '<img src="img/ft-1.jpg" width="18" height="18" alt="Personagem2">',
    created_at: '7 hours ago',
    upvotes: 3
  },
  {
    author: "Pasha Biceps",
    title: "Don't let bad process or structure kill great interfaces",
    url: "http://www.medium.com",
    category: 'Product Design',
    comments: '0 coments',
    classcor: 'corUm',
    foto: '<img src="img/ft-3.jpg" width="18" height="18" alt="Personagem2">',
    created_at: '2 days ago',
    isOwner: true,
    upvotes: 2
  }

    ]};

data.person.forEach(function(p){ 

  var post = "<section><span><a href='#'></a>"+p.upvotes+"</span><div><a     href="+p.url+">"+p.url+"</a><h1>"+p.title+"</h1><nav><a  href='#' id='bt-category' class="+ p.classcor +" title="+ p.category +">"+p.category+"</a><p>"+p.foto+"<a href='#' title="+p.author+">"+p.author+"</a>"+p.created_at+"<a  href='#' class='coments'>"+p.comments+"</a></p></nav></div></section>";

  document.querySelector('#dados').innerHTML += post;

});
}
  • Brother, what’s your question about Json? JSON is an array of objects. If you give a console.log in the date variable you will see it in its original state and you will be able to navigate it without difficulty.

  • So this is why I’m learning JSON, and they gave me this to do, I researched everything when it’s place to see examples and the only one that worked was one with table, but when I try to reproduce the same with HTML does not work, sorry to nubisse!!

  • imagine... Look, first understand the following. JSON is a format. That is, a way to store data. It could be for example XML. Knowing this, I will try to play an example of Json here as a response and you adapt your blz?

  • blz, vlw even, because I’m lost heheh

  • The problem is in assigning the value to variable postRow. You have single quotes where you should have double quotes, it doesn’t have the ; at the end. This all generates errors and so nothing is rendered.

  • you say there in the link tags? pq was the only way Dreamweaver did not error

  • I put an answer below, focusing on another way to consume JSON, which from what I saw is its difficulty. I think it’s easier to understand like this...

  • on the line where you have var postRow = . Your problem is not only understanding how JSON works, but programming itself.

  • @Filipemoraes If you mean space, is that I gave a enter there, but even without it it is not right

  • I recently chose to use Vuejs and AXIOS, you can take a look at this answer to see how simple everything is https://answall.com/a/308311/5704

Show 5 more comments

2 answers

1

Note that it is a very simple example and can be used in several ways...

var json = {
   person: [
   {
  "author": "Nobtaka Nukui",
  "title": "Want people to use your product? Use it yourself",
  "url": "http://www.medium.com",
  "category": "Product Design",
  "comments": 4,
  "created_at": 1460030400,
  "upvotes": 11
},
{
  "author": "Danil Ishutin",
  "title": "Font Size Idea: px at Root, rem for Components, em for Text Elements",
  "url": "http://www.css-tricks.com",
  "category": "ux_ui",
  "comments": 7,
  "created_at": 1459857600,
  "upvotes": 9
},
{
  "author": "Mikael Greif",
  "title": "What do you do with a failed project?",
  "url": "http://www.mika.el",
  "category": "discussion",
  "comments": 2,
  "created_at": 1460203200,
  "upvotes": 4
},
{
  "author": "Kenny Schrub",
  "title": "Some things can't be prototyped",
  "url": "http://www.mika.el",
  "category": "discussion",
  "comments": 25,
  "created_at": 1460203200,
  "isOwner": true,
  "upvotes": 4
},
{
  "author": "Jacky Mao",
  "title": "How to prototype without any tools",
  "url": "http://www.jackymao.wix",
  "category": "product_design",
  "comments": 0,
  "upvotes": 1
},
{
  "author": "Christopher Alesund",
  "title": "Case study: Redesigning the Folyo landing page",
  "url": "http://www.medium.com",
  "category": "case_study",
  "comments": 0,
  "created_at": 1460289600,
  "upvotes": 3
},
{
  "author": "Pasha Biceps",
  "title": "Don't let bad process or structure kill great interfaces",
  "url": "http://www.medium.com",
  "category": "product_design",
  "comments": 0,
  "created_at": 1460376000,
  "isOwner": true,
  "upvotes": 2
  }
 ]
};

//console.log(json);
for(var i=0;i< json.person.length; i++){
  var html = "<tr>";
  html +="<td>"+json.person[i].author+"</td>";
  html +="<td>"+json.person[i].title+"</td>";
  html +="<td>"+json.person[i].url+"</td>";
  html +="<td>"+json.person[i].upvotes+"</td>";
  html +="</tr>";
  $('table tbody').append(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <thead>
    <tr>
      <th>Author</th>
      <th>Title</th>
      <th>Url</th>
      <th>Upvotes</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

  • vlw I will try here

  • If really help, mark as answer paid? Hugs and good luck!

  • in fact doing so does not need javascript?

  • Yes, you do! In fact, he’s the one who’s taking the information from Json and playing in HTML

-1

To filter the data you can use search:

//Sintaxe:
var teste = 'exemplo'
teste.search('ex') //Retorna 0 que é a posição da primeira ocorrência do filtro
teste.search('Ex') //Retorna -1, ou seja, não foi encontrado
teste.search(/Ex/i) //Exemplo de busca com case-insensitive, retorna 0 

//No JSON, para buscar os autores que tenham a letra y ou Y:
for(var i = 0; i < json.person.length; i++) {
    if(json.person[i].author.search(/y/i) != -1) {
        //Mostra os dados
    }
}

To register use push:

//Sintaxe
var exemplo = [1, 2, 3]
exemplo.push(4)
console.log(exemplo) //Retorna [1, 2, 3, 4]

//Você pode usar push para adicionar objetos no JSON
json.person.push({
    author: 'nome exemplo',
    title: 'exemplo de titulp',
    url: 'https://google.com',
    category: 'minha categoria',
    comments: 0,
    created_at: 1460030400,
    upvotes: 0
})
//push() retorna o índice do cadastro, no caso 8

Read more about arrays

  • vlw bro I’ll give a studied

  • 1

    The answer does not help to answer the question. The most appropriate is to put in a comment, even so do not know what would help.

  • @Filipemoraes What answer, mine or William’s?

  • @user4451 Yours was a comment, so I am talking about William’s reply.

  • @Filipemoraes the main question is about the error, but he also asks for references about handling JSON, because this is not an answer?

  • Use the comment for this. The answer must be complete and not partial.

  • @Filipemoraes even if another previous answer has already healed the other half? being unnecessary repetition of the same

  • I do not know if it is a rule here of the stack, but I think there is no need for this discussion, even if he has not put another part I thank, because for whom is lost all help is welcome!!

  • While this link may answer the question, it is best to include the essential parts of the answer here and provide the link for reference. Replies per link only can be invalidated if the page with the link is changed. - Of Revision

  • That’s what you’re right

  • 1

    @rLinhares agree with this despite finding it difficult for w3s to change their links, so I edited the question with an example

  • @Guilhermecostamilam I tried to use the data you passed but could not, I did an update using the code I posted, only that the problem that it is only perfect if the code is directly in the HTML and not brought from Jason.

  • If the error happens only when the file is external to html the error is in loading it, take a look at this question, if the problem persists let us know

  • @Guilhermecostamilam I put another code there in the main post that now works, only missing now I filter by category and ready.

  • Create another question, do not use the same if this problem has been solved

  • @Guilhermecostamilam Yes, it’s just that sometimes I get a little afraid to do that, so they say I’m being redundant and close my post

Show 11 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.