Traverse all keys of a json

2

I want to go through all the keys of a json so that I can get all its values. Ex:

{
  "logistics_provider": "{{lp_name}}",
  "shipper": "{{co_common_name}}",
  "invoice_key": "{{ae_identifier}}",
  "invoice_series": "{{ae_identifier}}",
  "volume_number": "1",
   "events": [
  {
        "event_date": "{{ae_date}}",
        "original_code": "{{ae_code_event}}",
        "original_message": "{{ae_comment}}"
  }]
}

So I want the values {{lp_name}} , {{co_common_name}} etc ...

    
asked by anonymous 18.11.2016 / 14:51

2 answers

3

Adapting a little this response from SOen :

    var objeto =  {
      "logistics_provider": "{{lp_name}}",
      "shipper": "{{co_common_name}}",
      "invoice_key": "{{ae_identifier}}",
      "invoice_series": "{{ae_identifier}}",
      "volume_number": "1",
       "events": [
      {
            "event_date": "{{ae_date}}",
            "original_code": "{{ae_code_event}}",
            "original_message": "{{ae_comment}}"
      }]
    };

    var resultado = [];

    function percorrer(obj) {
      for (var propriedade in obj) {
        if (obj.hasOwnProperty(propriedade)) {
          if (typeof obj[propriedade] == "object") {
            percorrer(obj[propriedade]);
          } else {
            resultado.push(obj[propriedade]);
          }
        }
      }
    }

    percorrer(objeto);
    console.log(JSON.stringify(resultado));
    
18.11.2016 / 15:00
3

Given that the JSON framework is this, you can use for..in to read the keys and values of the two levels:

var obj = {
  "logistics_provider": "{{lp_name}}",
  "shipper": "{{co_common_name}}",
  "invoice_key": "{{ae_identifier}}",
  "invoice_series": "{{ae_identifier}}",
  "volume_number": "1",
  "events": [{
    "event_date": "{{ae_date}}",
    "original_code": "{{ae_code_event}}",
    "original_message": "{{ae_comment}}"
  }]
};

for (key in obj) { // obtém as chaves do objeto
  // se o valor for diferente de objeto (caso events)
  if (typeof obj[key] !== 'object') 
    console.log("Chave: " + key + " - Valor: " + obj[key]);
  else
    // se o valor for um array de objetos, é iterado o array
    // e as chaves de cada objeto
    obj[key].forEach(function(item) {
      for (key2 in item) {
        console.log("Chave: " + key2 + " - Valor: " + item[key2]);
      }
    });
}
    
18.11.2016 / 15:01