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

如何用Python更新JSON单个值?为空闲号码分配用户信息

问题:更新JSON中空的displayName字段

我有如下JSON文件内容(已补全格式):

[
  {
    "displayName": "",
    "Location": "Jacksonville",
    "directNumber": "+1 904-513-6504",
    "extension": "36504"
  }, 
  {
    "displayName": "Lawrence Curka",
    "Location": "Jacksonville",
    "directNumber": "+1 123-513-6508",
    "extension": "36508"
  },
  {
    "displayName": "Chris Brown",
    "Location": "Jacksonville",
    "directNumber": "+1 123-513-6511",
    "extension": "36511"
  }
]

我希望编写Python脚本遍历该JSON数据,找到未分配displayName的空闲号码并为其添加用户名。现有代码能找出所有空闲号码,但不知道如何更新单个键值:

with open('file.json') as json_file:
    data = json.load(json_file)
    user_count = 0

    for i in data:
        if i['displayName'] == "":
            print("Found Free Number: ", i['directNumber'])
            user_count += 1

    print("Free Number Count: ", user_count)

请问能否仅更新第一个JSON对象中空的displayName为指定用户名?


解决方案

完全可以直接修改对应字段的值,之后将更新后的JSON写回文件即可。修改后的脚本如下:

import json

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

# 遍历数据更新空displayName
user_count = 0
# 替换为你需要设置的用户名
target_username = "John Doe"

for item in data:
    if item['displayName'] == "":
        print(f"更新号码 {item['directNumber']} 的用户名为: {target_username}")
        # 直接修改字典字段值
        item['displayName'] = target_username
        user_count += 1
        # 如果只需要更新第一个空值,可在这里添加break跳出循环
        # break

print(f"共更新 {user_count} 个空闲号码")

# 将更新后的数据写回JSON文件
with open('file.json', 'w') as json_file:
    json.dump(data, json_file, indent=2)

关键说明:

  • 遍历JSON数组时,每个item是原数据字典的引用,直接修改item['displayName']会同步更新原数据列表中的对应元素
  • 如果只需要更新第一个空值,在修改后添加break语句即可停止遍历
  • 使用json.dump()写回文件时,indent=2参数保证输出的JSON格式美观易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:46:08