You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:13:08