Extract object list from JSON

Asked

Viewed 1,184 times

1

Good afternoon.

I have an application that makes a request in my database and returns a json. This json contains a list of objects, which in my case are products, I’m having difficulty to rescue the information because when I try to use a foreach to interact within the list and return the objects an error occurs. How can I redeem this information?

Attach a fragment of JSON:

{docs: Array(7977), warning: "no matching index found, create an index to optimize query time"}
docs: Array(7977)
[0 … 99]
0: {_id: "produto-1", descricao: "LANTERNA DIANT DIR", referencia: "KADETTE"}
1: {_id: "produto-10", descricao: "HELICE", referencia: "4044/46923"}
2: {_id: "produto-100", descricao: "BOMBA DE OLEO", referencia: "BO0205/10055"}
3: {_id: "produto-1000", descricao: "CABO DO TRATOMETRO", referencia: "229370"}

The code I tried to extract the object was:

this.localdb.find(req).then((result) => {
  if (result === undefined) {
    rej('Erro: Não foi possivel carregar os dados');
  } else {
    result.array.forEach(element => {
    console.log(element);
  });
    res(result);
}

The initial object was only to print in the log, but it presents the message: 'Cannot read Property 'foreach' of Undefined'

  • result.array is null. Make a debug or use console.log(result) to identify the variable value.

  • I think the array in the foreach should be Capital no?!

  • Leandrade, I’ve done these tests before and the syntax is ok. But it’s not working. The question is how to extract this information. The result is being filled in, and if I display with the console.log(result) it displays json. My doubt is how I can extract this information because the structure is more or less like this: ːDocs: 0: {_id: "product-1", Description: "DIANT DIR FLASHLIGHT", Reference: "KADETTE"} }

  • You can’t tell exactly what the return type of the Api is, it’s an array of objects, this syntax 0: {...} 1: {...} don’t know.

  • @Gustavomgu.Veloper your question has two answers, we operate by a system of merits and punctuation. If any of the answer is useful and answers your question you could accept it. If you do not know how to accept an answer see our Tour.

2 answers

1

Analyzing

In the question it is not clear what format your JSON document has for sure if it is really an array or if the tool you used to dump formatted the output of the data in an object.

Then I saw three possibilities for the format of your document:

1 . Being an object of objects

{"docs": {
    "0": {"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
    "1": {"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
    "2": {"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
    "3": {"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}}
}

2 . Being an object of an object array

{ "docs": [
   {"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
   {"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
   {"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
   {"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}]
}

3 . be simply an array of objects

[
  {"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
  {"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
  {"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
  {"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}
]

As I could not determine the exact format of the document by the question I decided to create a function that analyzes the three possible formats and displays a report of the products contained in the document.

Developing

The function is called logElements(doc, root) and accepts two strings as parameter doc is a string in one of the three formats described above and root the document in the first two formats.

This function created to understand the problem is based on the question code and was made so that it can be easily reintegrated into the original code.

Its function is to extract an object from the JSON document, passed as parameter doc, using the method JSON.parse(string) and check if it is an array(third case), if it is not array it converts the object to an array using the method Object.values(obj) the object identified byroot as an array conversion target. The function ends by reporting using the correct method syntax Array.prototype.forEach(callback(currentValue).

// Objeto de objetos
var jsonCaso1 = `{ "docs": {
"0": {"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
"1": {"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
"2": {"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
"3": {"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}
}}`;

// Objeto de uma array objetos 
var jsonCaso2 = `{ "docs": [
 {"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
 {"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
 {"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
 {"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}
]}`;

//Array de objetos
var jsonCaso3 = `[
 {"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
 {"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
 {"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
 {"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}
]`;


console.log("=".repeat(10) + "Teste JSON caso 1" + "=".repeat(10));
logElements(jsonCaso1 , "docs");

console.log("=".repeat(10) + "Teste JSON caso 2" + "=".repeat(10));
logElements(jsonCaso2 , "docs");

console.log("=".repeat(10) + "Teste JSON caso 3" + "=".repeat(10));
logElements(jsonCaso3);



function logElements(doc, root){
  // Convert JSON para objeto
  var obj = JSON.parse(doc);
  if (obj === undefined){
      console.log('Erro: Não foi possivel carregar os dados');
  } else {
      // Se o objeto convertido não for array converte o objeto cujo o nome ésta armazenado em root em array 
      if (!Array.isArray(obj)) obj = Object.values(obj[root]);

      // Imprime o relatório, note a sintaxe de forEach se o objeto já é um Array é só usar direto.
      obj.forEach(element => {
           console.log("\nProduto = " + element._id + "\nDescrição = " + element.descricao + "\nReferência = " + element.referencia + "\n" + "-".repeat(40));
      });
  }
}

Answer

Applying the concepts used to create the function logElements to your code and assuming that result is a string in JSON format probably obtained from a Nosql DB:

this.localdb.find(req).then((result) => {
  // Convert JSON para objeto
  var result = JSON.parse(doc);
  if (result === undefined) {
    rej('Erro: Não foi possivel carregar os dados');
  } else {
      // Se o objeto convertido não for array converte o objeto 
      if (!Array.isArray(result )) result = Object.values(result["docs"]);
         result.forEach(element => {
         console.log(element);
      });
    res(result);
 }
});
  • Thank you Augusto Vasques, your answer helped me a lot here. And sorry I was not as clear as possible in explaining my problem.

0

hmm... What you have there is not quite an Array, but you can do more or less like this:

var objetos = {
    docs : {
        0: {_id: "produto-1", descricao: "--", referencia: "--"},
        1: {_id: "produto-2", descricao: "--", referencia: "--"},
        2: {_id: "produto-3", descricao: "--", referencia: "--"},
        3: {_id: "produto-4", descricao: "--", referencia: "--"},
        4: {_id: "produto-5", descricao: "--", referencia: "--"},
        5: {_id: "produto-6", descricao: "--", referencia: "--"},
    }
}

Object.keys(objetos.docs).forEach(function(key, index){
    let doc = objetos.docs[key]
    console.log(key+' = '+doc._id);
})

I hope you understand at least a little bit of what I tried to do, I don’t think it’s exactly what you want, but it comes close.

As it comes to an Object, I take the 'Keys' which in this case is like the contents of these other objects within docs and from these Keys i individually pick up each object inside the foreach and do what I want (in the case of the example, a simple console.log()).

Browser other questions tagged

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