You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在IONIC中使用*ngFor从对象内的数组中获取对象

如何从嵌套的JSON对象数组中获取目标对象?

嘿,我来帮你搞定这个问题!从你给出的JSON结构来看,目标对象藏在contents下的quotes数组里,只需要逐层访问就能拿到它。我先把你的JSON结构清晰展示出来:

{
"success": { "total": 1 },
"contents": {
"quotes": [
{
"quote": "You can’t succeed coming to the potluck with only a fork.",
"author": "Dave Liniger",
"length": "64",
"tags": [ "inspire", "team-building", "tso-funny", "working-with-people" ],
"category": "inspire",
"title": "Inspiring Quote of the day",
"date": "2018-05-05",
"id": null
}
],
"copyright": "2017-19 theysaidso..."
}
}

下面给你举两个常用编程语言的实现例子:

JavaScript 实现

// 假设你已经将JSON解析为JavaScript对象,命名为jsonData
const jsonData = { /* 你的JSON内容 */ };

// 逐层访问:contents -> quotes数组 -> 第一个元素(数组索引从0开始)
const targetQuote = jsonData.contents.quotes[0];

// 现在可以轻松获取对象里的属性了
console.log(targetQuote.quote); // 输出名言内容
console.log(targetQuote.author); // 输出作者名称

Python 实现

import json

# 假设你有JSON格式的字符串,或者从文件读取了内容
json_str = '''{ "success": { "total": 1 }, "contents": { "quotes": [ { "quote": "You can’t succeed coming to the potluck with only a fork.", "author": "Dave Liniger", "length": "64", "tags": [ "inspire", "team-building", "tso-funny", "working-with-people" ], "category": "inspire", "title": "Inspiring Quote of the day", "date": "2018-05-05", "id": null } ], "copyright": "2017-19 theysaidso..." }'''

# 解析JSON字符串为Python字典
json_data = json.loads(json_str)

# 逐层访问:contents字典 -> quotes列表 -> 第一个元素
target_quote = json_data['contents']['quotes'][0]

# 获取目标属性
print(target_quote['quote'])
print(target_quote['author'])

核心思路就是逐层访问嵌套结构:先定位到外层的contents对象,再找到里面的quotes数组,最后通过数组索引(比如[0])取出数组中的目标对象。如果quotes数组包含多个元素,你可以用循环遍历每个对象来处理。

内容的提问来源于stack exchange,提问作者user2160886

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:35:12