Array reading

Asked

Viewed 81 times

2

I receive from an API the following result:

{
   "ShippingSevicesArray":[
      {
         "ServiceCode":"3",
         "ServiceDescription":"Transportadora Jadlog ",
         "Carrier":"Jadlog",
         "ShippingPrice":"12.09",
         "DeliveryTime":"3",
         "Msg":"Valor do Frete",
         "Error":false,
         "OriginalDeliveryTime":"3",
         "OriginalShippingPrice":"12.09",
         "ResponseTime":"371.2847"
      },
      {
         "ServiceCode":"DAY_1",
         "ServiceDescription":"Daytona Express",
         "Carrier":"Daytona Express",
         "ShippingPrice":"17.59",
         "DeliveryTime":"1",
         "Msg":"Ok",
         "Error":false,
         "OriginalDeliveryTime":"1",
         "OriginalShippingPrice":"17.590600",
         "ResponseTime":"542.6267"
      },
      {
         "ServiceCode":"04596",
         "ServiceDescription":"PAC (04596)",
         "Carrier":"Correios",
         "ShippingPrice":"18.72",
         "DeliveryTime":"5",
         "Msg":"Não foi encontrada precificação. ERP-013: Valor declarado nao permitido (valor minimo: 19,5, valor maximo: 3000)(-1).",
         "Error":false,
         "OriginalDeliveryTime":"5",
         "OriginalShippingPrice":"18.720000",
         "ResponseTime":"749.0625"
      },
      {
         "ServiceCode":"04553",
         "ServiceDescription":"Sedex (04553)",
         "Carrier":"Correios",
         "ShippingPrice":"22.23",
         "DeliveryTime":"2",
         "Msg":"Não foi encontrada precificação. ERP-013: Valor declarado nao permitido (valor minimo: 19,5, valor maximo: 10000)(-1).",
         "Error":false,
         "OriginalDeliveryTime":"2",
         "OriginalShippingPrice":"22.230000",
         "ResponseTime":"295.264"
      }
   ],
   "Timeout":0
}

But I’m not able to read as Javascript, I’m using the following code:

var person = json; //json tem o conteúdo acima                        
var i = 0;
var itens = '';                        
var len = person.length;
for (; i < len; ) {     
    itens += '<li>'+person["ShippingSevicesArray"][i]["ServiceDescription"]+'</li>';
    i++                           
}

$("#frete").append(itens);

Is returning the error:

"Cannot read property '0' of undefined" 

any suggestions on how to resolve?

I applied several examples found on the internet but was unsuccessful.

  • What happens if you make one console.log in the json? Does the console log an object or string in json format? Another error in the code is that len should receive the value of person.ShippingSevicesArray.length, nay person.length, but that’s not what’s causing your mistake.

  • it brings exactly the information I put up {"Shippingsevicesarray":......

  • Yes, it brings the information, but it is possible that this information is in the format of a string, which would justify the error you are having, because when trying to access the property ShippingSevicesArray of a string you would receive undefined, and when trying to access the property 0 of undefined, you would get the error Cannot read property '0' of undefined.

3 answers

1

You need to take the amount of list items by property ShippingSevicesArray, example:

person.ShippingSevicesArray.length

and then use the same code:

const person = {"ShippingSevicesArray":[{"ServiceCode":"3","ServiceDescription":"Transportadora Jadlog ","Carrier":"Jadlog","ShippingPrice":"12.09","DeliveryTime":"3","Msg":"Valor do Frete","Error":false,"OriginalDeliveryTime":"3","OriginalShippingPrice":"12.09","ResponseTime":"371.2847"},{"ServiceCode":"DAY_1","ServiceDescription":"Daytona Express","Carrier":"Daytona Express","ShippingPrice":"17.59","DeliveryTime":"1","Msg":"Ok","Error":false,"OriginalDeliveryTime":"1","OriginalShippingPrice":"17.590600","ResponseTime":"542.6267"},{"ServiceCode":"04596","ServiceDescription":"PAC (04596)","Carrier":"Correios","ShippingPrice":"18.72","DeliveryTime":"5","Msg":"Não foi encontrada precificação. ERP-013: Valor declarado nao permitido (valor minimo: 19,5, valor maximo: 3000)(-1).","Error":false,"OriginalDeliveryTime":"5","OriginalShippingPrice":"18.720000","ResponseTime":"749.0625"},{"ServiceCode":"04553","ServiceDescription":"Sedex (04553)","Carrier":"Correios","ShippingPrice":"22.23","DeliveryTime":"2","Msg":"Não foi encontrada precificação. ERP-013: Valor declarado nao permitido (valor minimo: 19,5, valor maximo: 10000)(-1).","Error":false,"OriginalDeliveryTime":"2","OriginalShippingPrice":"22.230000","ResponseTime":"295.264"}],"Timeout":0};

                     
var i = 0;
var itens = '';                        
var len = person.ShippingSevicesArray.length;

for (; i < len; ) {     
    itens += '<li>'+person["ShippingSevicesArray"][i]["ServiceDescription"]+'</li>';
    i++                           
}

$("#items").html(itens);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="items"></ul>

1


This error is not reproducible, so by error message I will try to deduce the error.

json be coming as a string. This means that it is not possible to access the property ShippingSevicesArray of json. First you should parse this string to convert it into an object, then access its properties, as follows:

var person = JSON.parse(json);

Now person receives an object, and you can access its properties normally.

var i = 0;
var itens = '';                        
var len = person.ShippingSevicesArray.length;

for (; i < len; ) {     
    itens += '<li>'+person.ShippingSevicesArray[i].ServiceDescription+'</li>';
    i++                           
}
$("#frete").append(itens);

Or sooner rather than later

var itens = person.ShippingSevicesArray.map(ss => `<li>${ss.ServiceDescription}</li>`);
$("#frete").append(itens);
  • Yeah that’s right I was coming as string and I didn’t heed it.

  • I appreciate the help

0

For your code to work, just replace:

var len = person.length;

For:

var len = Object.keys(person).length;

Browser other questions tagged

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