javascript - Node.JS:从 JSON 对象请求键值
问题描述
API_URL 显示如下:
{
"posts": [{
"id": "987f2bhfzu3r3f43fg",
"uuid": "g3g4g-4g34gd7f-40ae-96g43g82-65g34g43ccec94a566",
"title": "This is my title",
"tag": "thistag"
}]
}
const request = require('request');
request('API_URL', { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
console.log(body.posts);
});
还给我
[{
"id": "987f2bhfzu3r3f43fg",
"uuid": "g3g4g-4g34gd7f-40ae-96g43g82-65g34g43ccec94a566",
"title": "This is my title",
"tag": "thistag"
}]
如果我尝试console.log(body.posts.title);
在我的代码中返回
不明确的
我从谁那里得到title的键值?
解决方案
注意方括号 ( []
) - 你有一个包含单个元素的数组。您首先需要下标该元素,然后才能访问该字段:
console.log(body.posts[0].title)
// Here --------------^
推荐阅读
- python - 在 Pycharm 中,当我已经使用 pip install 安装它时,为什么找不到我的 NLTK 模块。(卸载 Python 3.8 到 3.7 安装 Tensorflow)
- linux - 转义在 sed 中的变量中定义的特殊字符
- algorithm - Branch & Bound 问题中矩阵约简的意义何在?
- php - 使用复选框删除多行
- android - 房间中的惰性和更新项目无法按预期工作
- android-studio - Android Studio Emulator (Flutter) - 每次键入时都会弹出虚拟键盘,包括没有文本字段的屏幕
- firebase - 如何从服务器上的 Firebase 功能访问 Google Cloud Storage
- docker - 如何在 docker-compose.yml 文件中设置持久数据
- android - 如何更改 TextView 的 drawableEnd 属性
- android - 不让我构建我的 android 项目,但让我在 Unity 2019.1.6f1 Personal 中调试它