求基于设备日/月筛选对应JSON数组并显示的实现方法
Alright, let's walk through how to solve this problem—reading your JSON schedule, matching it to the device's current day/month, and displaying the relevant entry. I'll cover the core logic and provide practical code examples for common platforms.
Core Approach Overview
The process breaks down into 4 key steps:
- Load and parse the JSON file into a usable data structure
- Retrieve the device's current day and month (formatted to match your JSON entries)
- Search the parsed JSON for an entry where the first two elements match the device's day/month
- Render the matched entry on your app's UI
Example 1: JavaScript (Web/Node.js)
If you're building a web app or using Node.js, here's a straightforward implementation:
async function loadAndDisplaySchedule() { try { // Step 1: Fetch and parse the JSON file const response = await fetch('your-schedule-file.json'); const scheduleEntries = await response.json(); // This will be an array of arrays // Step 2: Get current day/month (match JSON's string format) const today = new Date(); // Adjust padStart based on your JSON: use "" instead of "0" if your JSON uses "1" not "01" const currentDay = String(today.getDate()).padStart(2, '0'); const currentMonth = String(today.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed in JS // Step 3: Find the matching entry const matchedEntry = scheduleEntries.find(entry => { const entryDay = entry[0]; const entryMonth = entry[1]; return entryDay === currentDay && entryMonth === currentMonth; }); // Step 4: Display on UI const displayElement = document.getElementById('schedule-container'); if (matchedEntry) { // Clear existing content and render times displayElement.innerHTML = '<h3>Today\'s Schedule</h3>'; const timeList = document.createElement('ul'); matchedEntry.slice(2).forEach(time => { const listItem = document.createElement('li'); listItem.textContent = time; timeList.appendChild(listItem); }); displayElement.appendChild(timeList); } else { displayElement.textContent = 'No schedule available for today.'; } } catch (error) { console.error('Error loading schedule:', error); document.getElementById('schedule-container').textContent = 'Failed to load schedule data.'; } } // Run when the page loads window.addEventListener('DOMContentLoaded', loadAndDisplaySchedule);
Example 2: Kotlin (Android)
For Android apps using Kotlin, here's how you can implement this (assuming your JSON file is in the assets folder):
import android.os.Bundle import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import org.json.JSONArray import java.io.IOException import java.text.SimpleDateFormat import java.util.* class ScheduleActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_schedule) val scheduleContainer = findViewById<LinearLayout>(R.id.schedule_container) // Step 1: Load and parse JSON from assets val scheduleEntries = try { val inputStream = assets.open("schedule.json") val jsonString = inputStream.bufferedReader().use { it.readText() } JSONArray(jsonString) } catch (e: IOException) { showError(scheduleContainer, "Failed to load schedule.") return } // Step 2: Get current day/month (formatted to match JSON) val dateFormatter = SimpleDateFormat("dd MM", Locale.getDefault()) val dateParts = dateFormatter.format(Date()).split(" ") val currentDay = dateParts[0] val currentMonth = dateParts[1] // Step 3: Find matching entry var matchedEntry: JSONArray? = null for (i in 0 until scheduleEntries.length()) { val entry = scheduleEntries.getJSONArray(i) val entryDay = entry.getString(0) val entryMonth = entry.getString(1) if (entryDay == currentDay && entryMonth == currentMonth) { matchedEntry = entry break } } // Step 4: Display on UI matchedEntry?.let { entry -> val title = TextView(this).apply { text = "Today's Schedule" textSize = 20f setPadding(0, 0, 0, 16) } scheduleContainer.addView(title) for (i in 2 until entry.length()) { val timeView = TextView(this).apply { text = entry.getString(i) textSize = 16f setPadding(0, 8, 0, 8) } scheduleContainer.addView(timeView) } } ?: run { showError(scheduleContainer, "No schedule available for today.") } } private fun showError(container: LinearLayout, message: String) { val errorView = TextView(this).apply { text = message textSize = 16f } container.addView(errorView) } }
Key Notes to Avoid Issues
- Format Consistency: Double-check that your device's day/month string matches the format in your JSON. For example, if your JSON uses
"1"instead of"01"for the 1st day, remove thepadStart(in JS) or adjust the date formatter pattern to"d M"(in Kotlin). - Error Handling: Always account for cases where the JSON file can't be loaded, parsed, or no matching entry exists—this prevents crashes and keeps the user informed.
- Performance: If your JSON has a huge number of entries, consider optimizing the search (e.g., pre-process the data into a map like
{ "day-month": entry }for O(1) lookups instead of looping through every entry each time).
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

