Get values from a JSON in node.js

0

I'm having problems with this code in Node.js. I need to get the information found in "Contents" of the JSON but it gives me an error that says: "e.Contents.forEach is not a function" I guess it's a logical problem but I honestly do not know nothing happens to me, could you give me an example of how to solve it, please?

This is the JSON:

var jsonFile = {
"Notification": [
    {
        "Channel":1, 
        "Type":1,
        "Means":
            [{
                "Number":88888888,
                "Code":506
            }]
        ,
        "Contents":{
            "Message":"This is a message"
        }   
    }
    ] 
}

This is the code:

function Fe(jsonFile){
  jsonFile.Notification.forEach(e =>{
    e.Means.forEach(function(v){
      e.Contents.forEach(function(n){
        console.log(n.Message);
      })
})
}
    
asked by java005 06.09.2018 в 18:11
source

3 answers

1

The problem with your code is that if you look at the indentation, Message and subobjeto Contents are not inside the subobjeto Means (which is an array). Additionally neither Contents nor Message are fixes, so you can not make a forEach to them.

var jsonFile = {
"Notification": [
    {
        "Channel":1, 
        "Type":1,
        "Means":
            [{
                "Number":88888888,
                "Code":506
            }]
        ,
        "Contents":{
            "Message":"This is a message"
        }   
    }
    ] 
}

jsonFile.Notification.forEach(e =>{
    console.log(e.Contents);
    console.log(e.Contents.Message);
})

Always guide yourself in the indentation to know how to access the objects, in this case it helps if you represent it as a tree

                 Notification
              /      |       \        \
            /        |        \          \
          /          |         \             \ 
   Channel         Type        Means        Contents
   /                |         /     \               |
 1                  1      Number   Code          Message
                           |         |                 |
                      88888888      506         "This is a message"
    
answered by 06.09.2018 / 18:20
source
1

Do not forget to make the validations before to know if the properties of your object exist

var jsonFile = {
"Notification": [
    {
        "Channel":1, 
        "Type":1,
        "Means":
            [{
                "Number":88888888,
                "Code":506
            }]
        ,
        "Contents":{
            "Message":"This is a message"
        }   
    }
    ] 
};

var notas=jsonFile["Notification"][0]["Contents"];
console.log(JSON.stringify(notas));

'

    
answered by 06.09.2018 в 18:23
0

Making use of destructuring saves you a few lines.

const Fe = ( jsonFile ) =>
   jsonFile.Notification.forEach(({ Contents: { Message } }) =>
     console.log(Message);
   );
    
answered by 13.09.2018 в 01:45