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

如何去除Python生成的JSON文件中值的空白字符?

解决JSON值中多余空白字符的问题

你用separators参数没效果是因为它管的是JSON结构的分隔符空格(比如键值对之间、数组元素之间的空格),根本碰不到值本身的空白。要处理值里的多余空格,得在读取CSV数据的时候就清理——这些空白本来就是CSV单元格里带的。

直接修改你代码里遍历CSV行的部分,对每个字符串值做首尾空白去除:

import csv 
import json 

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []
      
    with open(csvFilePath, encoding='utf-8-sig') as csvf: 
        csvReader = csv.DictReader(csvf) 

        for row in csvReader: 
            # 清理每行中字符串值的首尾空白
            cleaned_row = {}
            for key, value in row.items():
                if isinstance(value, str):
                    cleaned_row[key] = value.strip()
                else:
                    cleaned_row[key] = value
            jsonArray.append(cleaned_row)
  
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 
        jsonString = json.dumps(jsonArray, indent=4, ensure_ascii=False)
        jsonf.write(jsonString)
          
csvFilePath = r'input.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)

也可以用更简洁的字典推导式实现同样效果:

for row in csvReader: 
    cleaned_row = {k: v.strip() if isinstance(v, str) else v for k, v in row.items()}
    jsonArray.append(cleaned_row)

这样处理后,生成的JSON里所有字符串值的首尾空白都会被去掉,比如"True "会变成"True",手机号的多余空格也会被清理干净。

内容的提问来源于stack exchange,提问作者user1348067

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:02:36