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

如何用Volley获取JSON嵌套数组内source的name字段值

Fixing the source.name Retrieval from NewsAPI

Hey there! I’ve worked with the NewsAPI a bunch, so let’s get that nested source.name field working for you.

First, let’s clarify the structure of the API response—you mentioned source is an array, but it’s actually a plain object nested inside each article. Here’s a simplified snippet of what the response looks like:

{
  "articles": [
    {
      "source": {
        "id": "associated-press",
        "name": "Associated Press"
      },
      "title": "Your Article Title",
      // Other article fields...
    }
  ]
}

Since you can already grab the first article, the fix is just one extra step to drill into the source object. Here are examples for two common languages:

JavaScript Example (Browser/Node.js)

fetch('https://newsapi.org/v2/top-headlines?q=trump&language=en&apiKey=954cfe1dd4db4f8fb19e425c12db324e')
  .then(res => res.json())
  .then(data => {
    // Always check if articles exist to avoid errors
    if (!data.articles || data.articles.length === 0) {
      console.log("No articles returned");
      return;
    }

    const firstArticle = data.articles[0];
    // Here's how you grab the source name
    const sourceName = firstArticle.source.name;
    
    console.log("First article source:", sourceName);
    console.log("First article title:", firstArticle.title);
  })
  .catch(err => console.error("Fetch error:", err));

Python Example

import requests

api_url = "https://newsapi.org/v2/top-headlines?q=trump&language=en&apiKey=954cfe1dd4db4f8fb19e425c12db324e"
response = requests.get(api_url)
data = response.json()

if not data.get("articles") or len(data["articles"]) == 0:
    print("No articles found")
else:
    first_article = data["articles"][0]
    # Access source name via dictionary keys
    source_name = first_article["source"]["name"]
    
    print(f"First article source: {source_name}")
    print(f"First article title: {first_article['title']}")

Key Notes:

  • The source property is an object, not an array—so you don’t need to use index notation like source[0] here. Just use dot notation (JS) or bracket notation (Python) to access .name directly.
  • Always add checks for empty articles arrays or missing source objects to prevent runtime errors (like if an article has no source data for some reason).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:25:49