Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

javascript - Access specific data on Json - NodeJS

I'm trying to access data from a json but i can't... I have tried some explanations i found on the internet, but i guess there is something wrong on my code.

I'm getting data from a sql server database using the following code:

async function getLogin1(Operador, Senha) { 
    try {
        let pool = await sql.connect(config);
        let getLogin1 = await pool.request()
            .input('input_parameter', sql.VarChar, Operador)
            .input('input_parameter1', sql.VarChar, Senha)
            .query("SELECT Codigo, Operador, Senha FROM Usuario where Operador = @input_parameter and Senha = @input_parameter1");
        return getLogin1.recordsets;
    }
    catch (error) {
        console.log(error);

    }
}

So i get the recordsets here and put in a json:

router.route("/Login1").get((request, response) => {
    console.log(request.body.operador);
    console.log(request.body.senha);
    Operador = request.body.operador;
    Senha = request.body.senha;

    dboperations.getLogin1(Operador, Senha).then(result => {
        console.log(Operador, Senha);
        response.json(result);
        var json = JSON.stringify(result);
        console.log(json);
    })

})

On the console it shows the json:

[[{"Codigo":1,"Operador":"Username","Senha":"123456"}]]

I would like to get the individual data (codigo, operador and senha) to put in a individual string each one, but i cant access the data. When I try like json[0] for example i get all the json (because my json has every info on the first position i guess), and when i try json.Codigo (for example) i get a "undefined" error.

What am i doing wrong and what the best way to solve?

And sorry for the low knowledge, this is my very first api.

(And yes, this is a login code and its not the best way to treat user data but its a very small system for intern use)

question from:https://stackoverflow.com/questions/65936712/access-specific-data-on-json-nodejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your JSON "result" is:

[[{"Codigo":1,"Operador":"MASTER","Senha":"TERA0205"}]]

So it is an array of array containing one object with keys Codigo, Operador, Senha.

To get the value of the Codigo of that object you would likely need to access it like

var CodigoVal = result[0][0].Codigo; // 1
var OperadorVal = result[0][0].Operador; // "MASTER"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...