如何用Python去除JSON文件输出中的空格与缩进?
解决JSON紧凑输出问题
要实现每个对象的键值对紧凑排列在同一行,你需要正确配置json.dump()的separators参数,并将indent设置为None(而非False),具体调整如下:
修正后的核心代码片段
# Step 3: Write the extracted data to a new JSON file with open('output.json', 'w') as file: json.dump(extracted_data, file, indent=None, separators=(',', ':'))
参数说明
indent=None: 指定不添加任何缩进或换行来格式化结构,确保输出整体紧凑。separators=(',', ':'): 移除逗号和冒号后的默认空格,让键值对、对象之间没有多余空白字符。
完整修正脚本
import json # Step 1: Read the JSON file with open('input.json', 'r') as file: data = json.load(file) # Step 2: Extract the specific data extracted_data = [] for token in data['tokens']: extracted_data.append({ 'symbol': token['symbol'], 'address': token['address'] }) # Step 3: Write the extracted data to a new JSON file with open('output.json', 'w') as file: json.dump(extracted_data, file, indent=None, separators=(',', ':'))
调整后生成的output.json会呈现如下紧凑格式:
[{"symbol":"ETH","address":"0x123..."},{"symbol":"BTC","address":"0x456..."}]
内容的提问来源于stack exchange,提问作者Jaurez
相关产品推荐
相关产品推荐

