Browse JSON JavaScript NodeJS

1

Good morning,

I modify the question.

How can I navigate through this JSON in NODEJS JavaScript:

{
  "subscriptionId" : "5a268a598dc68904bbc7b3cf",
  "originator" : "localhost",
  "contextResponses" : [
    {
      "contextElement" : {
        "type" : "Temperatura",
        "isPattern" : "false",
        "id" : "S_Temp001",
        "attributes" : [
          {
            "name" : "Tem_int",
            "type" : "float",
            "value" : 2,
            "metadatas" : [
              {
                "name" : "accuracy",
                "type" : "Float",
                "value": 2              }
            ]
          },
          {
            "name" : "Tem_out",
            "type" : "Integer",
            "value" : 1
          }
        ]
      },
      "statusCode" : {
        "code" : "200",
        "reasonPhrase" : "OK"
      }
    }
  ]
}

A greeting and thanks.

EDIT01

Right now the answer I have is:

[ [ 'S_Temp001', 'Temperatura', 'Tem_int', 'float', 2, 'accuracy', 'Float',2 ] ]

I am saving it in BD in such a way (it works correctly):

var sql = "INSERT INTO inver (fiwareServicePath, entityId,  entityType, attrName, attrType, attrValue) VALUES ?";

connection.query(sql, [tmp], function(err, rows) {
          if(err)
          {
            throw err;
            console.log('Error al Conectar' + error);
          }
          else
          {
            res.status(200).json(rows);
          }
        });

Now my question: I'm just saving what belongs to attributes[0] I need to generate another array separated by, and inserted inside [] in the same array of tmp is to say something like this:

var tmp= [['S_Temp001', 'Temperatura', 'Tem_int', 'float', 2, 'accuracy',
'Float',2],['S_Temp001', 'Temperatura', 'Tem_out', 'Integer', 1, 'accuracy',
'Float',2]];

For metadata I have added this in the code that you have given me:

   json["contextResponses"][i].contextElement.attributes[0].metadatas[0].name,
     json["contextResponses"][i].contextElement.attributes[0].metadatas[0].type,
     json["contextResponses"][i].contextElement.attributes[0].metadatas[0].value]);

I need it this way to insert this list in my database and each array from within a new row, so that would be the example I have set for you:

I guess I have to generate a new for within this for (var i = 0; i < json["contextResponses"].length; i++) to go through the attributes and add them as a new array with the structure that I mentioned earlier.

var tmp= [['S_Temp001', 'Temperatura', 'Tem_int', 'float', 2, 'accuracy',
    'Float',2],['S_Temp001', 'Temperatura', 'Tem_out', 'Integer', 1, 'accuracy',
    'Float',2]];

I do not know if I've explained myself well.

thanks.

EDIT02 Solution

Good morning,

I have already found the solution, I add it in case it could be worth someone.

  var tmp2 = [];
      for (var i = 0; i < params.contextResponses.length; i++) {
        for (var j = 0; j < params.contextResponses[i].contextElement.attributes.length; j++) {
          for (var k = 0; k < params.contextResponses[i].contextElement.attributes[j].metadatas.length; k++) {
            console.log("nuevo log antes de petar: " + params["contextResponses"][i].contextElement.attributes[j].metadatas[k].value);

            tmp2.push([params.contextResponses[i].contextElement.id,
                     params.contextResponses[i].contextElement.type,
                     params.contextResponses[i].contextElement.attributes[j].name,
                     params.contextResponses[i].contextElement.attributes[j].type,
                     params.contextResponses[i].contextElement.attributes[j].value,
                     params.contextResponses[i].contextElement.attributes[j].metadatas[k].name,
                     params.contextResponses[i].contextElement.attributes[j].metadatas[k].type,
                     params.contextResponses[i].contextElement.attributes[j].metadatas[k].value]);
            console.log("tmp2 --> ",tmp2);
          }
        }
    }

Greetings and thanks for the help.

    
asked by Manolait 05.12.2017 в 13:48
source

2 answers

3
  let json = {
    "subscriptionId" : "5a268a598dc68904bbc7b3cf",
    "originator" : "localhost",
    "contextResponses" : [
      {
        "contextElement" : {
          "type" : "Temperatura",
          "isPattern" : "false",
          "id" : "S_Temp001",
          "attributes" : [
            {
              "name" : "Tem_int",
              "type" : "float",
              "value" : 2,
              "metadatas" : [
                {
                  "name" : "accuracy",
                  "type" : "Float",
                  "value": 2              }
              ]
            },
            {
              "name" : "Tem_out",
              "type" : "Integer",
              "value" : 1
            }
          ]
        },
        "statusCode" : {
          "code" : "200",
          "reasonPhrase" : "OK"
        }
      },
      {
        "contextElement" : {
          "type" : "Temperatura",
          "isPattern" : "false",
          "id" : "S_Temp002",
          "attributes" : [
            {
              "name" : "Tem_int1",
              "type" : "float1",
              "value" : 3,
              "metadatas" : [
                {
                  "name" : "accuracy1",
                  "type" : "Floa1t",
                  "value": 3              }
              ]
            },
            {
              "name" : "Tem_out",
              "type" : "Integer",
              "value" : 1
            }
          ]
        },
        "statusCode" : {
          "code" : "200",
          "reasonPhrase" : "OK"
        }
      }
    ]
  };
  for (let ele in json) {
    //aquí para los que son objetos
    if (typeof(json[ele]) == 'object') {
      eachobject(json[ele]);
    } else {
      console.log('ele --> ', ele, ' - ', json[ele]);
      console.log('typo del ele --> ', typeof(json[ele]));
      console.log(' --------------------- ');
    }
  }

  function eachobject(json) {
    for (let ele in json) {
      if (typeof(json[ele]) == 'object') {
        eachobject(json[ele]);
      } else {
        console.log('ele --> ', ele, ' - ', json[ele]);
        console.log('typo del ele --> ', typeof(json[ele]));
        console.log(' --------------------- ');
      }
    }
  }

  let tmp = [];
  for (let i = 0; i < json["contextResponses"].length; i++) {
    console.log("Attributes --> ", json["contextResponses"][i]);
    tmp.push([json["contextResponses"][i].contextElement.id,
         json["contextResponses"][i].contextElement.type,
         json["contextResponses"][i].contextElement.attributes[0].name,
         json["contextResponses"][i].contextElement.attributes[0].type,
         json["contextResponses"][i].contextElement.attributes[0].value,
         json["contextResponses"][i].contextElement.attributes[0].metadatas[0].name,
         json["contextResponses"][i].contextElement.attributes[0].metadatas[0].type,
         json["contextResponses"][i].contextElement.attributes[0].metadatas[0].value]);
    console.log("tmp --> ",tmp);
  }

Modify the JSON thinking less about what you need to see it, and at the end add a for in which the DATA is in the format you need (you can do the same as a way to do it in case I do not know exactly what you need). Even so, let me know if it is not what you need and if it is possible to give me a little more details to give a more accurate answer.
I hope if you have not been able to solve it yet, I hope this will help you or if you have an easier way to do what you want, share :) PS: It's only to go through the whole object if you need more things to notify.
PS: Sorry the delay had not had much time and an update left me smeared on my note xD.

    
answered by 11.12.2017 / 16:06
source
1

If you only require certain values of the json, you could use destructuring, here is an example of what I mean:

var json = {
    "name": {
        "first": "Yosuke",
        "family": "Kyra"
    },
    "birth": {
        "year": 1982,
        "month": 12,
        "day": 5
    }
}
// Destructuring
var {name: { family: familyName }, birth: {day: birthDay}} = json
console.log(familyName) // return Kyra
console.log(birthDay) // return 5

More on the topic = > link

    
answered by 06.12.2017 в 23:26