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

如何使用Ajax与jQuery过滤JSON响应并提取前5条数据生成日期和地表温度数组

Alright, let's tackle this. Even though the JSON structure uses dates as top-level keys (which is a bit unconventional), we can still easily extract the data you need to build your labels and data arrays. Here's the modified code with step-by-step explanations:

Solution Code
$.ajax({
  dataType: "json",
  type: "GET",
  url: "https://www.infoclimat.fr/public-api/gfs/json?_ll=43.60426,1.44367&_auth=VkwDFAB%2BVnQALVRjDngELQRsAzZaLFJ1B3sBYgFvVisCZ1czA2QAYFY%2FVisOIQUwAy4EYA80AjlTNgZmXy1fI1Y3A24AZFY2AGxUNw47BC8EKAN%2BWmRSdQd7AWQBbFY3An9XMQNiAHxWOFYwDjsFLwMxBGUPOAIlUy8GYF80Xz9WNQNlAGpWMABtVDUOOgQvBCgDZVpkUmgHNwFjAWxWYQIwV2YDMgBrVj1WMw43BS8DNARkDzMCPVM0BmNfNF86VioDeAAaVkcAclR2DnwEZQRxA35aMFI0BzA%3D&_c=d2cc2bd980a89404afabf2e9b204309c",
  success: function(json) {
    // Step 1: Filter out only the date-time keys from the response
    const dateKeys = Object.keys(json).filter(key => 
      /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(key)
    );

    // Step 2: Get the first 5 dates (sort first if you need guaranteed chronological order)
    const top5Dates = dateKeys
      .sort((a, b) => new Date(a) - new Date(b)) // Optional: ensure correct time order
      .slice(0, 5);

    // Step 3: Initialize our target arrays
    const labels = [];
    const data = [];

    // Step 4: Populate arrays with date strings and corresponding surface temperatures
    top5Dates.forEach(date => {
      labels.push(date);
      // Use optional chaining to safely access nested fields, default to null if missing
      const surfaceTemp = json[date]?.temperature?.sol ?? null;
      data.push(surfaceTemp);
    });

    // Check the results in console
    console.log("Labels array:", labels);
    console.log("Surface temperature data array:", data);
  },
  error: function(result, statut, error) {
    console.log(error);
  }
});
Key Explanations
  • Filtering Date Keys: The response includes metadata fields like request_state and message, so we use a regex to filter only keys that match the YYYY-MM-DD HH:MM:SS date-time format. This ensures we only process the time-stamped data entries.
  • Sorting (Optional): If you want to be 100% sure the dates are in chronological order (even if the API returns them out of order), we add a sort step using new Date(a) - new Date(b) to compare timestamps numerically.
  • Safe Data Extraction: Using optional chaining (?.) prevents errors if a date entry is missing the temperature or sol field. The nullish coalescing operator (??) sets a default null value if those fields are absent, so your arrays stay consistent.
  • Building Arrays: We loop through the first 5 dates, pushing each date string to labels and its corresponding surface temperature to data—exactly the structure you requested.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 09:17:46