Query in Json file

Asked

Viewed 937 times

-1

I’m making a list of cities and states via JSON. I always create a table in the database to return this information. But today I’m making direct to the file JSON. The layout of the states file:

[{"ID": "1",
"Nome": "Afonso Cláudio",
"Estado": "8"
},
 {
"ID": "2",
"Nome": "Água Doce do Norte",
"Estado": "8"
},
 {
"ID": "3",
"Nome": "Águia Branca",
"Estado": "8"
},
 {
"ID": "4",
"Nome": "Alegre",
"Estado": "8"
}, etc]

What I need and am not getting, and return all cities that have the same key value Estado.

The consultation I carry out as follows:

$.getJSON("<?php echo base_url();?>assets/admin/json/Cidades.json", {'Estado':2}, function(json) {
  var options = "<select name='cidade' id='cidade' class='form-control show-tick'>";
  $.each(json, function(key, value){
   options += '<option value="' + value.Sigla + '">' + value.Nome + '</option>';
  });
  options += '</select>';
  $("#selectCidades").html(options);            
});

So the way it is the filtering doesn’t happen with the key ID informed. Obs: the value 2 of the parameter reported and only of example, this value comes from a variable filled by select states

  • Possible duplicate of recover data from JSON file

  • @RORSCHACH This marking of the question of the possible duplicate does not solve my problem, I have already done as described in the answer and it does not work.

  • What language do you have on the server? PHP + Mysql?

  • @Sergio Sim. And that I have saved only the cities registered in the bank, so u did not want to create 2 more tables for this.

1 answer

1

If you do the filtering on the server is better, because you already pass the information that Estado searches. But you can do this on the client, using .filter(), thus:

json = json.filter(obj => obj.Estado == 2)

An example would be:

const estado = 2;
$.getJSON("<?php echo base_url();?>assets/admin/json/Cidades.json", {'Estado': estado}, function(json) {
    const html = json.filter(obj => obj.Estado == estado).reduce((select, obj) => {
    return select + '<option value="' + value.Sigla + '">' + value.Nome + '</option>';
  }, "<select name='cidade' id='cidade' class='form-control show-tick'>") + "</select>";

  $("#selectCidades").html(html);
});
  • So. When I am on the pc I will try to implement. I was unaware of the JSON filter. More I believe I will have to make several changes there.

Browser other questions tagged

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