I get a json in a callback and I want to get the value of a property

0

How about I have the following code:

function login(req, res){
    req.getConnection((err, conexion)=>{
    if(err) return next(err);
    conexion.query('select * from tabla where id=?', req.body.id, (err, dato)=>{
      res.status(200).send({  campos: dato });
    });
  });
}

the json datum throws me the following:

{
    "campos": [
        {
            "id": 12,
            "campo1": "rulo",
            "campo2": "a$10$gIoFFPgXcDoJ07CN1qq",
            "campo2": "administrador"
        }
    ]
}

and I want to take the value of the field2.

already try with a for and foreach, but I can not access this data ...

thanks in advance.

    
asked by razadi 11.02.2018 в 20:39
source

2 answers

3

You can not, at least not as you have defined it.

The Shared JSON is not valid because there can be no keys duplicates (just as an object can not have two properties with the same name). When a duplicate key is found, the browser will try to solve the problem, keeping the last value:

var datos = {
    "campos": [
        {
            "id": 12,
            "campo1": "rulo",
            "campo2": "a$10$gIoFFPgXcDoJ07CN1qq",
            "campo2": "administrador"
        }
    ]
};

console.log(datos);

If you have a key / property that has more than one value, you should put it as an array of values instead of duplicating keys, something like this:

var datos = {
    "campos": [
        {
            "id": 12,
            "campo1": "rulo",
            "campo2": [
                       "a$10$gIoFFPgXcDoJ07CN1qq",
                       "administrador"
                      ]
        }
    ]
};

console.log(datos);

That JSON is already valid and then you can access campo2 how to access any array: campo2[0] will return "to $ 10 $ gIoFFPgXcDoJ07CN1qq" and campo2[1] will return "administrator".

    
answered by 11.02.2018 в 21:11
0

As you said above, in the first instance the JSON is poorly defined for the purpose of using it with javascript, so if you have access to the client's api that sends the data, I would suggest changing that.

If impossible, there is an alternative. The values are coupled the moment the chain reaches the server and becomes an object. This is done automatically since you apparently use the express framework.

The solution would be not to use express, but to use the born class of node.js http.Server, to capture the body through the events "data" and "end" and to parse the text obtained with the function JSON.parse (text, reviver).

The reviver argument is a function that will allow you to analyze each of the variables when they become an object. Check out: link

    
answered by 13.02.2018 в 23:33