gpt4 book ai didi

json - 在nodejs中解析json响应

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:58 24 4
gpt4 key购买 nike

我是初学者,正在学习 javascript,从未遇到过解析 json 数组。我有以下字符串

[{"_id":"5810abfec95a8743ec237fab","credentials":[{"_id":"5810abfec95a8743ec237fab","username":"sam"}]}]

我尝试遵循,

     //using following middle-ware as well
let app = express();
const collectioName = "credentials";
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));

//i get 'result' from one of query from mongodb
let response = JSON.parse(result);
console.log("got res " +response.credentials);

我还尝试通过以下方式获取数据

 for (var i=0; i<response['credentials'].length; i++){
console.log("got res " +response['credentials'][i]);
}

我需要从上面的 json 响应中获取用户名及其值。我想知道从此类 json 响应获取数据的正确方法是什么。

请提出建议

最佳答案

查看上面的答案后,我得到了一些线索,我认为这也应该有效,这为我节省了迭代时间,因为数据结构将仅返回一个 json 对象来匹配相应的凭据(因为数据库中不能存在相同的凭据) )。

   let response = JSON.parse(result);
var data=response[0].credentials;
let username = data[0].username;
let password = data[0].password;
console.log("username : " +username + "password : " +password );

关于json - 在nodejs中解析json响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40395075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com