如何用Python将含无引号键的TXT文件转换为JSON?
Convert Unquoted Key TXT to JSON Using Python
Converting your TXT file (which uses unquoted keys and lacks commas between pairs) to valid JSON can be done reliably with a combination of string processing and a YAML parser (since YAML natively supports unquoted keys). Here's a step-by-step solution:
Approach
- Add Missing Commas: The input lacks commas between key-value pairs (both top-level and nested). We'll use a state machine to insert commas correctly, avoiding any changes inside quoted strings.
- Wrap in Curly Braces: Convert the content into a valid YAML flow mapping by wrapping it in
{}. - Parse with YAML: Use PyYAML to parse the modified content into a Python dictionary.
- Convert to JSON: Use Python's built-in
jsonmodule to convert the dictionary to formatted JSON.
Full Code
import yaml import json def add_missing_commas(content): in_quote = False result = [] i = 0 n = len(content) after_value = False # Tracks if we just finished a value (string or block) while i < n: char = content[i] if char == '"': in_quote = not in_quote result.append(char) after_value = not in_quote # True if we just closed a string i += 1 elif char == '}' and not in_quote: result.append(char) after_value = True i += 1 elif char.isalpha() and not in_quote and after_value: # Insert comma before starting a new key after a value result.append(',') result.append(char) after_value = False i += 1 elif char.isspace() and not in_quote: result.append(char) i += 1 else: result.append(char) after_value = False i += 1 return ''.join(result) # Step 1: Read input file with open('input.txt', 'r') as f: input_content = f.read().strip() # Step 2: Add commas between all key-value pairs content_with_commas = add_missing_commas(input_content) # Step 3: Wrap in braces to make valid YAML flow mapping yaml_content = f"{{ {content_with_commas} }}" # Step 4: Parse YAML into a Python dictionary data = yaml.safe_load(yaml_content) # Step 5: Convert to formatted JSON json_content = json.dumps(data, indent=4) # Step 6: Write output to JSON file with open('output.json', 'w') as f: f.write(json_content) print("Conversion complete! Check output.json for results.")
How It Works
- add_missing_commas: This function iterates through the input, tracking if it's inside a quoted string. It inserts commas whenever it detects a new key starting right after a value (either a closed string or block).
- YAML Parsing: PyYAML handles unquoted keys seamlessly, converting the modified content into a Python dict without manual string manipulation of keys.
- JSON Conversion:
json.dumpstakes the dict and outputs properly formatted JSON with quoted keys, correct commas, and indentation.
Requirements
Install PyYAML first if you don't have it:
pip install pyyaml
Example Output
For your sample input, the resulting output.json will look like this:
{ "name": { "first_name": "random" }, "addresses": { "location": { "locality": "India", "street_address": "xyz", "postal_code": "300092", "full_address": "street 1 , abc,India" } }, "projects": { "url": "www.githib.com" } }
内容的提问来源于stack exchange,提问作者Nish
相关产品推荐
相关产品推荐

