如何用Python将特定格式文本文件转换为指定JSON数据?
Got it, let's solve this problem step by step. Here's a practical, easy-to-implement solution using Python—perfect for this kind of text-to-JSON conversion task.
Step-by-Step Explanation & Code
1. Read and Clean the Input File
First, we'll read the text file, strip out any extra whitespace or empty lines to avoid formatting issues that might break our conversion.
2. Map Lines to JSON Fields
- The first line directly becomes the
namevalue in our target JSON. - For every subsequent line, split the line into a key-value pair (using the first colon as the separator—this way we don't accidentally break values that might contain colons later).
- Trim whitespace from both keys and values to match your target JSON's clean, consistent formatting.
3. Generate and Save the JSON
Convert our processed dictionary into a properly formatted JSON string, and optionally save it to a file for later use.
Here's the full working code:
import json # Replace 'your_input.txt' with your actual file path with open('your_input.txt', 'r') as input_file: # Read all lines, strip whitespace, and skip empty lines cleaned_lines = [line.strip() for line in input_file if line.strip()] # Initialize our result dictionary json_data = {} # Handle the first line as the 'name' field if cleaned_lines: json_data['name'] = cleaned_lines[0] # Process each remaining line into key-value pairs for line in cleaned_lines[1:]: # Split only at the first colon to preserve colons in values key_part, value_part = line.split(':', 1) # Trim whitespace from key and value json_data[key_part.strip()] = value_part.strip() # Convert to formatted JSON (indent=2 makes it human-readable; remove for compact output) formatted_json = json.dumps(json_data, indent=2) # Print the result to verify print(formatted_json) # Optional: Write the JSON to an output file with open('output.json', 'w') as output_file: output_file.write(formatted_json)
Testing with Your Example Input
If your input text file looks like this:
Samuels heard
patient id : 7898
received date: 06/22/2019
firstname : scott deny
dob : 06/22/2019
Running the code will output exactly the JSON you need:
{ "name": "Samuels heard", "patient id": "7898", "received date": "06/22/2019", "firstname": "scott deny", "dob": "06/22/2019" }
This code handles minor formatting inconsistencies (like varying spaces around colons) and skips empty lines, so it's robust for most real-world cases.
内容的提问来源于stack exchange,提问作者dev ooty

