-1

I'm training to work with json and I'm trying to get some values from. That looks like this:

{
    "p:FatturaElettronica": {
        "$": {
            "xmlns:p": "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2",
            "xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
            "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
            "versione": "FPR12",
            "xsi:schemaLocation": "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2 fatturaordinaria_v1.2.xsd"
        },
        "FatturaElettronicaHeader": [
            {
                "DatiTrasmissione": [
                    {
                        "IdTrasmittente": [
                            {
                                "IdPaese": [
                                    "IT"
                                ],
                                "IdCodice": [
                                    "01895030995"
                                ]
                            }
                        ],
                        "ProgressivoInvio": [
                            "0HVHG"
                        ],
                        "FormatoTrasmissione": [
                            "FPR12"
                        ],
                        "CodiceDestinatario": [
                            "J6URRTW"
                        ]
                    }
                ],
                "CedentePrestatore": [
                    {
                        "DatiAnagrafici": [
                            {
                                "IdFiscaleIVA": [
                                    {
                                        "IdPaese": [
                                            "IT"
                                        ],
                                        "IdCodice": [
                                            "12345678127"
                                        ]
                                    }
                                ],
                                "CodiceFiscale": [
                                    "1127"
                                ],
                                "Anagrafica": [
                                    {
                                        "Denominazione": [
                                            "GE."
                                        ]
                                    }
                                ],
                                "RegimeFiscale": [
                                    "RF01"
                                ]
                            }
                        ],
                        "Sede": [
                            {
                                "Indirizzo": [
                                    "Via T. Fusco"
                                ],
                                "NumeroCivico": [
                                    "1"
                                ],
                                "CAP": [
                                    "846"
                                ],
                                "Comune": [
                                    "LAME"
                                ],
                                "Provincia": [
                                    "CZ"
                                ],
                                "Nazione": [
                                    "IT"
                                ]
                            }
                        ],
                        "Contatti": [
                            {
                                "Telefono": [
                                    "+39 09"
                                ],
                                "Fax": [
                                    "+39 09"
                                ],
                                "Email": [
                                    "XXXX@hotmail.it"
                                ]
                            }
                        ]
                    }
                ],
                "CessionarioCommittente": [
                    {
                        "DatiAnagrafici": [
                            {
                                "IdFiscaleIVA": [
                                    {
                                        "IdPaese": [
                                            "IT"
                                        ],
                                        "IdCodice": [
                                            "03084390792"
                                        ]
                                    }
                                ],
                                "CodiceFiscale": [
                                    "AAAAAAAA"
                                ],
                                "Anagrafica": [
                                    {
                                        "Nome": [
                                            "R"
                                        ],
                                        "Cognome": [
                                            "S"
                                        ]
                                    }
                                ]
                            }
                        ],
                        "Sede": [
                            {
                                "Indirizzo": [
                                    "VIA TIMAVO "
                                ],
                                "CAP": [
                                    "88"
                                ],
                                "Comune": [
                                    "LAMEZ"
                                ],
                                "Provincia": [
                                    "CZ"
                                ],
                                "Nazione": [
                                    "IT"
                                ]
                            }
                        ]
                    }
                ],
                "TerzoIntermediarioOSoggettoEmittente": [
                    {
                        "DatiAnagrafici": [
                            {
                                "IdFiscaleIVA": [
                                    {
                                        "IdPaese": [
                                            "IT"
                                        ],
                                        "IdCodice": [
                                            "01895030995"
                                        ]
                                    }
                                ],
                                "Anagrafica": [
                                    {
                                        "Denominazione": [
                                            "CompEd "
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ],
                "SoggettoEmittente": [
                    "TZ"
                ]
            }
        ],
        "FatturaElettronicaBody": [
            {
                "DatiGenerali": [
                    {
                        "DatiGeneraliDocumento": [
                            {
                                "TipoDocumento": [
                                    "TD01"
                                ],
                                "Divisa": [
                                    "EUR"
                                ],
                                "Data": [
                                    "2019-12-21"
                                ],
                                "Numero": [
                                    "1777"
                                ],
                                "ImportoTotaleDocumento": [
                                    "30.71"
                                ],
                                "Causale": [
                                    "Fattura Vendita Accompagnatoria"
                                ],
                                "Art73": [
                                    "SI"
                                ]
                            }
                        ],
                        "DatiTrasporto": [
                            {
                                "CausaleTrasporto": [
                                    "VENDITA"
                                ],
                                "NumeroColli": [
                                    "2"
                                ],
                                "Descrizione": [
                                    "A VISTA"
                                ],
                                "DataInizioTrasporto": [
                                    "2019-12-21"
                                ]
                            }
                        ]
                    }
                ],
                "DatiBeniServizi": [
                    {
                        "DettaglioLinee": [
                            {
                                "NumeroLinea": [
                                    "1"
                                ],
                                "CodiceArticolo": [
                                    {
                                        "CodiceTipo": [
                                            "INTERNO"
                                        ],
                                        "CodiceValore": [
                                            "8013170502498"
                                        ]
                                    }
                                ],
                                "Descrizione": [
                                    "PNP BUSTE TRASP. 40X60 PZ 100"
                                ],
                                "Quantita": [
                                    "1.00000000"
                                ],
                                "UnitaMisura": [
                                    "PC"
                                ],
                                "PrezzoUnitario": [
                                    "9.83610000"
                                ],
                                "PrezzoTotale": [
                                    "9.84"
                                ],
                                "AliquotaIVA": [
                                    "22.00"
                                ]
                            },
                            {
                                "NumeroLinea": [
                                    "2"
                                ],
                                "CodiceArticolo": [
                                    {
                                        "CodiceTipo": [
                                            "INTERNO"
                                        ],
                                        "CodiceValore": [
                                            "15017"
                                        ]
                                    }
                                ],
                                "Descrizione": [
                                    "TOVAGLIETTE CARTAPAGLIA 30x40 500 PZ"
                                ],
                                "Quantita": [
                                    "1.00000000"
                                ],
                                "UnitaMisura": [
                                    "PZ"
                                ],
                                "PrezzoUnitario": [
                                    "6.96720000"
                                ],
                                "PrezzoTotale": [
                                    "6.97"
                                ],
                                "AliquotaIVA": [
                                    "22.00"
                                ]
                            },
                            {
                                "NumeroLinea": [
                                    "3"
                                ],
                                "CodiceArticolo": [
                                    {
                                        "CodiceTipo": [
                                            "INTERNO"
                                        ],
                                        "CodiceValore": [
                                            "8014032035314"
                                        ]
                                    }
                                ],
                                "Descrizione": [
                                    "CAPRICE ORO TONDI  DIAM.30 PZ 2"
                                ],
                                "Quantita": [
                                    "4.00000000"
                                ],
                                "UnitaMisura": [
                                    "PZ"
                                ],
                                "PrezzoUnitario": [
                                    "1.06560000"
                                ],
                                "PrezzoTotale": [
                                    "4.26"
                                ],
                                "AliquotaIVA": [
                                    "22.00"
                                ]
                            },
                            {
                                "NumeroLinea": [
                                    "4"
                                ],
                                "CodiceArticolo": [
                                    {
                                        "CodiceTipo": [
                                            "INTERNO"
                                        ],
                                        "CodiceValore": [
                                            "8055329171339"
                                        ]
                                    }
                                ],
                                "Descrizione": [
                                    "BASTONCINI LEGNO GOLDEN HILL"
                                ],
                                "Quantita": [
                                    "5.00000000"
                                ],
                                "UnitaMisura": [
                                    "PZ"
                                ],
                                "PrezzoUnitario": [
                                    "0.81970000"
                                ],
                                "PrezzoTotale": [
                                    "4.10"
                                ],
                                "AliquotaIVA": [
                                    "22.00"
                                ]
                            }
                        ],
                        "DatiRiepilogo": [
                            {
                                "AliquotaIVA": [
                                    "22.00"
                                ],
                                "ImponibileImporto": [
                                    "25.17"
                                ],
                                "Imposta": [
                                    "5.54"
                                ],
                                "EsigibilitaIVA": [
                                    "I"
                                ]
                            }
                        ]
                    }
                ],
                "DatiPagamento": [
                    {
                        "CondizioniPagamento": [
                            "TP02"
                        ],
                        "DettaglioPagamento": [
                            {
                                "ModalitaPagamento": [
                                    "MP01"
                                ],
                                "DataRiferimentoTerminiPagamento": [
                                    "2019-12-21"
                                ],
                                "GiorniTerminiPagamento": [
                                    "0"
                                ],
                                "DataScadenzaPagamento": [
                                    "2019-12-21"
                                ],
                                "ImportoPagamento": [
                                    "30.71"
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
}

My desired result is to extract the values in the child elements and put them in a table to display in the browser. For starting, let's say I would like to put the values in an array, for example:

 ['IT','01895030995']

I really confuse how to get the values from the more internal child of this json. Maybe I should convert different to do so, because previously it was an XMLFile that I converted like this:

convert.parseString(xmlFile, (err, result) => {
  if(err) {
      throw err;
  }

  // `result` is a JavaScript object
  
  // convert it to a JSON string
  const json = JSON.stringify(result, null, 4);

I tried with forEach method, for loop and Object.keys/values trying to get at least a first result. In all the cases didn't work, it will console.log or undefined for thousands times or some numbers which I don't understand how....

Hoping someone could help.... thanks in advance!

Jack
  • 1
  • 3
  • To access only `IT` and `01895030995`, please try: `console.log(xmlFile["p:FatturaElettronica"].FatturaElettronicaHeader[0].DatiTrasmissione[0].IdTrasmittente[0].IdPaese[0], xmlFile["p:FatturaElettronica"].FatturaElettronicaHeader[0].DatiTrasmissione[0].IdTrasmittente[0].IdCodice[0]);`. I could not test it out though, the data provided in the question is invalid format (because it is incomplete, I think). Good luck with that file, though. :-) – jsN00b May 26 '22 at 15:12
  • Yes sir, thanks for the help... I tried and it gives an error TypeError: Cannot read properties of undefined (reading 'FatturaElettronicaHeader'... you're right anyway, the file is incomplete....I just updated the complete file here.... before I thought I couldn't because it is longer than 16000 lines, bue here it is – Jack May 26 '22 at 15:25
  • Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – gre_gor May 26 '22 at 15:30

1 Answers1

0

Presented below is one possible way to achieve the desired objective.

Code Snippet

// method to collect string values
const collectAllValues = (arr, res = []) => {
  // append result "res" with any "string" elt in array "arr"
  const r = [
    ...res,
    ...(
      arr?.filter(
        elt => typeof elt !== 'object'
      ) ?? []
    )
  ];
  // filter out "arr" elements that are "objects"
  const nx = arr?.filter(
    elt => typeof elt === 'object'
  ) ?? [];
  // if "objects" exist in "arr" elements-list
  // use ".reduce()" to iterate over the filtered "arr"
  // then, for each object, use ".reduce()" to 
  // iterate over values that are arrays and make
  // recursive call to this method & return the value
  if (nx && nx.length) {
    return (
      nx.reduce(
        (acc, ob) => ([
          ...acc,
          Object.values(ob)
          .filter(v => v && Array.isArray(v))
          .reduce((ac2, ar) => ([...ac2, ...collectAllValues(ar)]), acc)
          .flat()
        ]),
        r
      )
    );
  } else return r;
  // if no "objects" exist, simply return earlier
  // result "r"
};

const xmlFile = {
  "p:FatturaElettronica": {
    "$": {
      "xmlns:p": "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2",
      "xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
      "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
      "versione": "FPR12",
      "xsi:schemaLocation": "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2 fatturaordinaria_v1.2.xsd"
    },
    "FatturaElettronicaHeader": [{
      "DatiTrasmissione": [{
        "IdTrasmittente": [{
          "IdPaese": [
            "IT"
          ],
          "IdCodice": [
            "01895030995"
          ]
        }],
        "ProgressivoInvio": [
          "0HVHG"
        ],
        "FormatoTrasmissione": [
          "FPR12"
        ],
        "CodiceDestinatario": [
          "J6URRTW"
        ]
      }],
      "CedentePrestatore": [{
        "DatiAnagrafici": [{
          "IdFiscaleIVA": [{
            "IdPaese": [
              "IT"
            ],
            "IdCodice": [
              "12345678127"
            ]
          }],
          "CodiceFiscale": [
            "1127"
          ],
          "Anagrafica": [{
            "Denominazione": [
              "GE."
            ]
          }],
          "RegimeFiscale": [
            "RF01"
          ]
        }],
        "Sede": [{
          "Indirizzo": [
            "Via T. Fusco"
          ],
          "NumeroCivico": [
            "1"
          ],
          "CAP": [
            "846"
          ],
          "Comune": [
            "LAME"
          ],
          "Provincia": [
            "CZ"
          ],
          "Nazione": [
            "IT"
          ]
        }],
        "Contatti": [{
          "Telefono": [
            "+39 09"
          ],
          "Fax": [
            "+39 09"
          ],
          "Email": [
            "XXXX@hotmail.it"
          ]
        }]
      }],
      "CessionarioCommittente": [{
        "DatiAnagrafici": [{
          "IdFiscaleIVA": [{
            "IdPaese": [
              "IT"
            ],
            "IdCodice": [
              "03084390792"
            ]
          }],
          "CodiceFiscale": [
            "AAAAAAAA"
          ],
          "Anagrafica": [{
            "Nome": [
              "R"
            ],
            "Cognome": [
              "S"
            ]
          }]
        }],
        "Sede": [{
          "Indirizzo": [
            "VIA TIMAVO "
          ],
          "CAP": [
            "88"
          ],
          "Comune": [
            "LAMEZ"
          ],
          "Provincia": [
            "CZ"
          ],
          "Nazione": [
            "IT"
          ]
        }]
      }],
      "TerzoIntermediarioOSoggettoEmittente": [{
        "DatiAnagrafici": [{
          "IdFiscaleIVA": [{
            "IdPaese": [
              "IT"
            ],
            "IdCodice": [
              "01895030995"
            ]
          }],
          "Anagrafica": [{
            "Denominazione": [
              "CompEd "
            ]
          }]
        }]
      }],
      "SoggettoEmittente": [
        "TZ"
      ]
    }],
    "FatturaElettronicaBody": [{
      "DatiGenerali": [{
        "DatiGeneraliDocumento": [{
          "TipoDocumento": [
            "TD01"
          ],
          "Divisa": [
            "EUR"
          ],
          "Data": [
            "2019-12-21"
          ],
          "Numero": [
            "1777"
          ],
          "ImportoTotaleDocumento": [
            "30.71"
          ],
          "Causale": [
            "Fattura Vendita Accompagnatoria"
          ],
          "Art73": [
            "SI"
          ]
        }],
        "DatiTrasporto": [{
          "CausaleTrasporto": [
            "VENDITA"
          ],
          "NumeroColli": [
            "2"
          ],
          "Descrizione": [
            "A VISTA"
          ],
          "DataInizioTrasporto": [
            "2019-12-21"
          ]
        }]
      }],
      "DatiBeniServizi": [{
        "DettaglioLinee": [{
            "NumeroLinea": [
              "1"
            ],
            "CodiceArticolo": [{
              "CodiceTipo": [
                "INTERNO"
              ],
              "CodiceValore": [
                "8013170502498"
              ]
            }],
            "Descrizione": [
              "PNP BUSTE TRASP. 40X60 PZ 100"
            ],
            "Quantita": [
              "1.00000000"
            ],
            "UnitaMisura": [
              "PC"
            ],
            "PrezzoUnitario": [
              "9.83610000"
            ],
            "PrezzoTotale": [
              "9.84"
            ],
            "AliquotaIVA": [
              "22.00"
            ]
          },
          {
            "NumeroLinea": [
              "2"
            ],
            "CodiceArticolo": [{
              "CodiceTipo": [
                "INTERNO"
              ],
              "CodiceValore": [
                "15017"
              ]
            }],
            "Descrizione": [
              "TOVAGLIETTE CARTAPAGLIA 30x40 500 PZ"
            ],
            "Quantita": [
              "1.00000000"
            ],
            "UnitaMisura": [
              "PZ"
            ],
            "PrezzoUnitario": [
              "6.96720000"
            ],
            "PrezzoTotale": [
              "6.97"
            ],
            "AliquotaIVA": [
              "22.00"
            ]
          },
          {
            "NumeroLinea": [
              "3"
            ],
            "CodiceArticolo": [{
              "CodiceTipo": [
                "INTERNO"
              ],
              "CodiceValore": [
                "8014032035314"
              ]
            }],
            "Descrizione": [
              "CAPRICE ORO TONDI  DIAM.30 PZ 2"
            ],
            "Quantita": [
              "4.00000000"
            ],
            "UnitaMisura": [
              "PZ"
            ],
            "PrezzoUnitario": [
              "1.06560000"
            ],
            "PrezzoTotale": [
              "4.26"
            ],
            "AliquotaIVA": [
              "22.00"
            ]
          },
          {
            "NumeroLinea": [
              "4"
            ],
            "CodiceArticolo": [{
              "CodiceTipo": [
                "INTERNO"
              ],
              "CodiceValore": [
                "8055329171339"
              ]
            }],
            "Descrizione": [
              "BASTONCINI LEGNO GOLDEN HILL"
            ],
            "Quantita": [
              "5.00000000"
            ],
            "UnitaMisura": [
              "PZ"
            ],
            "PrezzoUnitario": [
              "0.81970000"
            ],
            "PrezzoTotale": [
              "4.10"
            ],
            "AliquotaIVA": [
              "22.00"
            ]
          }
        ],
        "DatiRiepilogo": [{
          "AliquotaIVA": [
            "22.00"
          ],
          "ImponibileImporto": [
            "25.17"
          ],
          "Imposta": [
            "5.54"
          ],
          "EsigibilitaIVA": [
            "I"
          ]
        }]
      }],
      "DatiPagamento": [{
        "CondizioniPagamento": [
          "TP02"
        ],
        "DettaglioPagamento": [{
          "ModalitaPagamento": [
            "MP01"
          ],
          "DataRiferimentoTerminiPagamento": [
            "2019-12-21"
          ],
          "GiorniTerminiPagamento": [
            "0"
          ],
          "DataScadenzaPagamento": [
            "2019-12-21"
          ],
          "ImportoPagamento": [
            "30.71"
          ]
        }]
      }]
    }]
  }
};

console.log(
'get sample 2 items only:\n[', xmlFile["p:FatturaElettronica"].FatturaElettronicaHeader[0].DatiTrasmissione[0].IdTrasmittente[0].IdPaese[0], ', ', xmlFile["p:FatturaElettronica"].FatturaElettronicaHeader[0].DatiTrasmissione[0].IdTrasmittente[0].IdCodice[0], '];');

console.log(
  'collect all values:\n',
  Object.values(xmlFile["p:FatturaElettronica"])
  .filter(v => v && Array.isArray(v))
  .reduce((acc, ar) => ([...acc, ...collectAllValues(ar)]), [])
  .flat()
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Inline comments added to the snippet above.

jsN00b
  • 3,584
  • 2
  • 8
  • 21
  • 1
    with your help jsN00b I solve the issue and I was able to proceed with the project.. your way worked well for my desired objective. Thank you very much! – Jack Jun 04 '22 at 12:53