Python遍历数组创建JSON文件及格式化输出代码技术咨询
Solution: Iterate Over Location Array to Generate Formatted JSON Files
It looks like you're working with an API to fetch location-specific trends and want to save each result as a nicely formatted JSON file—great use case! Your current code works for a single location, but we can streamline it and add iteration to handle your entire location_array. Let's fix up the code to avoid redundant file operations and loop through all locations.
Revised Code
import json # Assume your location array is defined here (e.g., location IDs from the API) location_array = [1, 23424977, 23424975] # Example: Global, NYC, LA for idx, location_id in enumerate(location_array, start=1): try: # Fetch trends data for the current location trends_data = api.trends_place(id=location_id) # Create a unique, descriptive filename filename = f"trends_location_{idx}.json" # Or use location_id: f"{location_id}_trends.json" # Write directly to the file with pretty formatting—no intermediate files needed! with open(filename, "w") as outfile: json.dump(trends_data, outfile, indent=4, sort_keys=True) print(f"Successfully saved data to {filename}") except Exception as e: print(f"Error processing location ID {location_id}: {str(e)}")
Key Improvements Over Your Original Code
- Iteration with
enumerate: Loops through every element inlocation_array, assigning a unique index to each for filename uniqueness. - Eliminates Redundant Steps: We skip the intermediate
placeInfo.jsonfile and directly write formatted JSON to the final output. No need to dump, load, re-dump, and re-load—json.dump()handles formatting directly! - Error Handling: Wraps the API call and file operation in a
try/exceptblock to catch issues like failed API requests or file permission errors. - Clear Filenames: Uses the index (or location ID, if you prefer) to create unique, meaningful filenames so you can easily map files to their corresponding locations.
Optional: If You Need to Work With Parsed Data
If you want to inspect or manipulate the parsed data before saving (like your original code did with indexing), you can do this without extra file operations:
# Inside the loop, after fetching trends_data: parsed_data = trends_data # The API response is already a Python dict/list pretty_json = json.dumps(parsed_data, indent=4, sort_keys=True) # Use parsed_data here for indexing or modifications print(f"Number of trends for location {idx}: {len(parsed_data[0]['trends'])}") # Write the formatted JSON to file with open(filename, "w") as outfile: outfile.write(pretty_json)
This keeps your code clean, efficient, and focused on your goal of generating one JSON file per location in your array.
内容的提问来源于stack exchange,提问作者Andrew DeNooyer
相关产品推荐
相关产品推荐

