如何遍历嵌套JSON并提取newsid、headline等属性
undefined Issue When Extracting News Data from Your JSON Hey there! Let's break down why you're getting undefined and how to pull out those news properties you need.
The Root Problem
Looking at your JSON structure, the newslist isn't an array—it's an object with string-numeric keys ("1", "2") that each hold a news item. When you tried dt.newsalert[0].newslist.headline, you were trying to access a headline property directly on newslist, which doesn't exist. That's why you got undefined.
Solution 1: Extract All News Items
If you want to get every news entry's newsid, headline, and newscode, use Object.values() to convert the newslist object's values into an array, then iterate over it:
const json_string = '{"newsalert":[{"newslist":{"1":{"newsid":"4321","headline":"Great White Shark Found","newscode":"GWS","newstime":"10:04:32"},"2":{"newsid":"8031","headline":"Polar Bear Escaped","newscode":"PBE","newstime":"09:28:03"}}}]}'; const dt = JSON.parse(json_string); // Convert newslist object values to an array of news items const allNews = Object.values(dt.newsalert[0].newslist); // Loop through each item to extract properties allNews.forEach(news => { console.log(`News ID: ${news.newsid}`); console.log(`Headline: ${news.headline}`); console.log(`News Code: ${news.newscode}`); console.log("-------------------"); });
Solution 2: Extract a Specific News Item
If you need just one specific entry (like the one with key "1"), access it directly using the key:
const dt = JSON.parse(json_string); const targetNews = dt.newsalert[0].newslist["1"]; console.log(targetNews.headline); // Outputs: "Great White Shark Found" console.log(targetNews.newsid); // Outputs: "4321" console.log(targetNews.newscode); // Outputs: "GWS"
Key Takeaway
Always double-check your JSON structure! newslist is an object here, not an array—so you either convert its values to an array for bulk processing, or use the exact key to grab individual items.
内容的提问来源于stack exchange,提问作者ernie

