OSPF文本转JSON出现冗余空字典问题求助
Hey there! I see you're having trouble converting your OSPF Link-State Database text into clean JSON—those redundant empty dictionaries like {"items": []} or {"items": [null]} are definitely annoying. Let's fix this together.
Root Cause
The issue is straightforward: your clean.txt still contains blank lines (including lines with only spaces/tabs), and your Python script is processing these empty lines as valid input, resulting in those unwanted empty structures in the final JSON.
Step-by-Step Solutions
1. First: Fully Clean Your clean.txt File
Before running the Python script, ensure clean.txt has no empty lines or whitespace-only lines. You can do this with a quick command-line tool, or handle it directly in Python.
Option A: Command-Line Preprocessing
Use sed or awk to strip all empty/whitespace-only lines:
# Using sed (works on Linux/macOS) sed '/^[[:space:]]*$/d' clean.txt > cleaned_final.txt # Using awk (cross-platform) awk 'NF' clean.txt > cleaned_final.txt
This creates a new file cleaned_final.txt with no empty lines to feed into your script.
Option B: Clean Lines Directly in Python
If you prefer handling cleaning within your script, modify the file-reading step to filter out empty lines:
with open("clean.txt", "r") as f: # Strip whitespace from each line, and only keep non-empty lines valid_lines = [line.strip() for line in f if line.strip()]
Use valid_lines instead of raw file content for your parsing logic.
2. Modify Your Python Script to Skip Empty Entries
Even with pre-cleaned files, adding checks in your parsing logic ensures you don't accidentally generate empty structures. Here's an example of a adjusted parsing script:
import json # Initialize base JSON structure ospf_data = {"ospf_lsdb_entries": []} current_entry = {} with open("cleaned_final.txt", "r") as file: for line in file: line = line.strip() # Skip any remaining empty lines (just in case) if not line: # Save the current entry if it has content, then reset if current_entry: ospf_data["ospf_lsdb_entries"].append(current_entry) current_entry = {} continue # Your existing parsing logic (adjust to match your LSDB format) # Example: splitting key-value pairs separated by colon if ":" in line: key, value = line.split(":", 1) current_entry[key.strip()] = value.strip() # Add the last entry if it exists if current_entry: ospf_data["ospf_lsdb_entries"].append(current_entry) # Write clean JSON output with open("myjson.json", "w") as outfile: json.dump(ospf_data, outfile, indent=2)
3. Verify the Result
After running the modified script, open myjson.json and confirm:
- No
{"items": []}or{"items": [null]}entries - All JSON entries map to actual LSDB entries from your original file
Key Takeaway
The core fix is ensuring no empty lines or whitespace-only lines are processed by your script. Combining pre-cleaning the text file with adding checks in your Python logic will eliminate those redundant empty structures entirely.
内容的提问来源于stack exchange,提问作者chenoi

