将JSON对象中int类型id值转为string类型以解决解码错误
解决JSON解析错误并将int类型id转为string类型
第一步:修复JSON语法错误
你遇到的json.decoder.JSONDecodeError是因为提供的JSON存在语法问题,具体包括:
- 部分对象末尾有多余的** trailing逗号**,比如
{"categoryLabel": "Scene",}最后的逗号不符合JSON规范 - 结构层级错误:
imageData的data数组闭合后多了一个],外层也存在多余的}
修复后的合法JSON示例如下:
{ "data": { "imageData": { "data": [ { "id": 1998459, "url": "https://some_url", "isInspirational": "true", "classifications": [ { "categoryLabel": "Scene" }, { "categoryLabel": "Contemporary" }, { "categoryLabel": "Rectangle" }, { "categoryLabel": "Square" }, { "categoryLabel": "Trapezoid" }, { "categoryLabel": "Triangle" }, { "categoryLabel": "Hard" }, { "categoryLabel": "Soft" }, { "categoryLabel": "Smooth" }, { "categoryLabel": "Stripe" }, { "categoryLabel": "Primary_Color" }, { "categoryLabel": "Calm" }, { "categoryLabel": "Light" }, { "categoryLabel": "Interior" }, { "categoryLabel": "Residential" } ] } ] } } }
第二步:用Python批量转换int类型id为string
通过递归遍历JSON结构,定位所有key为id且值为int类型的字段,将其转为string。具体代码如下:
import json def convert_ids_to_string(obj): if isinstance(obj, dict): for key, value in obj.items(): if key == "id" and isinstance(value, int): obj[key] = str(value) else: convert_ids_to_string(value) elif isinstance(obj, list): for item in obj: convert_ids_to_string(item) return obj # 读取修复后的JSON文件(也可直接传入JSON字符串) with open("your_file.json", "r", encoding="utf-8") as f: json_data = json.load(f) # 执行id类型转换 processed_data = convert_ids_to_string(json_data) # 保存处理后的JSON with open("processed_file.json", "w", encoding="utf-8") as f: json.dump(processed_data, f, indent=2)
可选:自动修复不规范JSON
如果原始JSON语法错误较多,可使用demjson库自动修复:
- 安装库:
pip install demjson - 修复+转换的代码:
import demjson import json # 读取不规范的JSON内容 with open("invalid_json.json", "r", encoding="utf-8") as f: invalid_json_str = f.read() # 修复JSON格式 json_data = demjson.decode(invalid_json_str) # 调用转换函数处理id processed_data = convert_ids_to_string(json_data) # 保存最终结果 with open("fixed_and_processed.json", "w", encoding="utf-8") as f: json.dump(processed_data, f, indent=2)
Atom IDE查找替换方案(简单场景适用)
若想用Atom批量处理规整的JSON,可开启正则匹配:
- 打开查找替换面板(Ctrl+F),勾选
.*正则选项 - 查找模式:
"id":\s*(\d+) - 替换模式:
"id": "$1"
注:该方式仅适用于JSON格式相对规范的场景,若存在语法错误(如trailing逗号),正则匹配可能失效。
内容的提问来源于stack exchange,提问作者sanster9292
相关产品推荐
相关产品推荐

