如何将JSON转换为指定格式的键值对Properties文件并解决缩进问题?
Solution: Convert JSON to Indented Key-Value Properties File
Hey there! The issue with your current text-replacement approach is that it relies on string pattern matching—this can break if the JSON format varies (like extra spaces, quoted values with special characters) and makes precise indentation control tricky. Instead, let’s use Python’s built-in json module to properly parse the JSON data, then generate the properties file with exact, consistent indentation.
Step-by-Step Solution
Here’s a revised version of your updateConfigFile function that fixes the indentation problem and handles conversion reliably:
import json def updateConfigFile(filename, indent=4): # Load and parse the JSON content into a Python dictionary with open(filename, 'r') as json_file: config_dict = json.load(json_file) # Create the indent string based on your desired spacing indentation = ' ' * indent # Generate each line of the properties file in "key = value" format with indentation properties_lines = [] for key, value in config_dict.items(): properties_lines.append(f"{indentation}{key} = {value}") # Join all lines into a single string properties_content = '\n'.join(properties_lines) # Write the result back to the file (or a new .properties file) # Option 1: Overwrite the original JSON file with open(filename, 'w') as props_file: props_file.write(properties_content) # Option 2: Write to a new .properties file (uncomment below if needed) # with open(filename.replace('.json', '.properties'), 'w') as props_file: # props_file.write(properties_content)
How This Works
- Safe JSON Parsing: Using
json.load()converts the JSON file directly into a Python dictionary, so we avoid messy string hacks and reliably access key-value pairs regardless of JSON syntax variations. - Controlled Indentation: We create an
indentationstring (e.g., 4 spaces) that’s prepended to every line—no guesswork or error-prone replacements needed. - Flexible Output: Choose to overwrite the original file or save to a new
.propertiesfile by using the relevant code block.
Example Output
For your sample JSON:
{"id":"0","meta":"down","type":"1","direction":"0","interval":"1800"}
With indent=4, the output will look exactly like this:
id = 0 meta = down type = 1 direction = 0 interval = 1800
Customization Tips
- Adjust the
indentparameter (e.g.,indent=2for 2-space indentation) to match your project’s formatting requirements. - If your JSON has nested structures, you can extend this function with recursion to handle nested keys (e.g.,
parent.child = value), but that’s a separate use case!
内容的提问来源于stack exchange,提问作者Pinaki Mukherjee
相关产品推荐
相关产品推荐

