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

如何用Python 3.7替换JSON文件中"id":null为"id":na?

Python 3.7 JSON字段替换实现方案

需求

编写Python 3.7代码处理JSON文件:将objects数组中所有"id": null的字段替换为"id": "na";对象无id字段或id值不为null时跳过。

原始JSON示例

{
 "objects": [
    {
        "version": "1",
        "id": null,
        "date": 1
    },
    {
        "version": "1",
        "id": "1xx1",
        "date": 1
    }
 ]
}

期望处理结果

{
 "objects": [
    {
        "version": "1",
        "id": "na",
        "date": 1
    },
    {
        "version": "1",
        "id": "1xx1",
        "date": 1
    }
 ]
}

尝试的问题代码

import json

with open('file.json',encoding='utf8') as in_file:
data = json.load(in_file)

for c in data['objects']:      # read all elements in object into c
if c = "\"id\"": null,:       # check to see if element in c is "id": null,
    data[c] = "\"id\"": na,   # replace c with

问题分析与修正代码

原代码问题点

  1. 缩进错误:Python依赖缩进区分代码块,with、for、if语句块均未正确缩进
  2. 逻辑错误:遍历objects的对象后,错误尝试直接匹配字符串形式的键值对,正确做法是检查对象的键和对应值
  3. 类型混淆:JSON的null在Python中会被解析为None,不能直接用null判断;且JSON中没有na字面量,必须用字符串"na"
  4. 赋值错误:应直接修改遍历到的对象的id字段,而非操作data[c]

修正后的代码

import json

# 读取JSON文件
with open('file.json', encoding='utf8') as in_file:
    data = json.load(in_file)

# 遍历objects数组中的每个对象
for obj in data['objects']:
    # 检查对象存在id字段且值为None(对应JSON的null)
    if 'id' in obj and obj['id'] is None:
        obj['id'] = 'na'

# 将修改后的数据写入文件(保留格式化缩进)
with open('file.json', 'w', encoding='utf8') as out_file:
    json.dump(data, out_file, indent=2, ensure_ascii=False)

代码说明

  • json.load()将JSON文件解析为Python字典/列表,其中null转为None
  • 先判断'id' in obj避免因键不存在抛出KeyError
  • json.dump()的indent=2保证输出JSON格式美观,ensure_ascii=False支持非ASCII字符
  • 用字符串'na'赋值,确保输出符合JSON语法规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:05:43