Uncategorized

javascript – (simple, but strange) Problem looping through a big JSON data file JS, Python



Context

Hello, I have a JSON file with a list of objects similar to this:

[{
"Codigo":"01",
"Descricao":"Animais vivos.",
"Data_Inicio":"01/04/2022",
"Data_Fim":"31/12/9999",
"Tipo_Ato":"Res Camex",
"Numero_Ato":"272",
"Ano_Ato":"2021"
},
{
"Codigo":"0102.31",
"Descricao":"-- Reprodutores de raça pura",
"Data_Inicio":"01/04/2022",
"Data_Fim":"31/12/9999",
"Tipo_Ato":"Res Camex",
"Numero_Ato":"272",
"Ano_Ato":"2021"
}, .....]

the list above have 15075 objects. I’m making a script that check if “Codigo” have more than 6 caracteres, if yes, it will pop it out of the list.

Problem

I’ve tried to make it using javaScript and python, and have the same problem in both languages. when executing the following code:

javaScript

for(var i= 0; i <Nomenclaturas.length; i++){
   if(Nomenclaturas[i].Codigo.length>6){
      Nomenclaturas.splice(i,1)
   }
}
console.log(Nomenclaturas.length)
//result = 8180

the code in JavaScript doesn’t make it’s job, because some objects in my list with Codigo.length>6 aren’t removed. The strange part is if I repeat the same code chunk above multiple times, it works:

for(var i= 0; i <Nomenclaturas.length; i++){
   if(Nomenclaturas[i].Codigo.length>6){
      Nomenclaturas.splice(i,1)
   }
}
console.log(Nomenclaturas.length)
//result = 8180
for(var i= 0; i <Nomenclaturas.length; i++){
   if(Nomenclaturas[i].Codigo.length>6){
      Nomenclaturas.splice(i,1)
   }
}
console.log(Nomenclaturas.length)
//result = 4646

for(var i= 0; i <Nomenclaturas.length; i++){
   if(Nomenclaturas[i].Codigo.length>6){
      Nomenclaturas.splice(i,1)
   }
}
console.log(Nomenclaturas.length)
//result = 2984

when I repeat the code chunk 7 times, it do what it suppose to do. I’ve tried the same script in python:

for i, nome in enumerate(nomeclaturas):
    if(len(nome['Codigo'])>6):
        del nomeclaturas[i]
print(len(nomeclaturas))
#result = 8180

And I’ve the same problem, it doesn’t work by complete, and It works when I repeat the code “for” code chunk.

my operational system:
Windows 11 home 64-bit (10.0, build 22621)

you can download this JSON here:
https://portalunico.siscomex.gov.br/classif/#/nomenclatura/tabela?perfil=publico

Selection “tabela vigente” and “JSON”



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *