如何用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
sourceproperty is an object, not an array—so you don’t need to use index notation likesource[0]here. Just use dot notation (JS) or bracket notation (Python) to access.namedirectly. - Always add checks for empty
articlesarrays or missingsourceobjects to prevent runtime errors (like if an article has no source data for some reason).
内容的提问来源于stack exchange,提问作者Luke C
相关产品推荐
相关产品推荐

