python - Python 错误:写入 json 文件时无法将“列表”对象隐式转换为 str
问题描述
我有一个 json 文件,其中一个字段的列表数据如下所示 { "broker_address":"0.0.0.0", "serial_id": "YYMMSSSSSSVV", "auto_foc": true, "timer": [0,23, 30] }
我正在为计时器字段获取用户输入,因此我想用从用户接收到的输入值替换计时器数据。在尝试它时,我收到以下错误
Traceback (most recent call last):
File "test.py", line 23, in <module>
time, final)
TypeError: Can't convert 'list' object to str implicitly
我的代码片段如下
import json
import os
import time
val = input("Enter your value: ")
print(val)
str1 = " "
with open('/home/pi/config.json', 'r+') as filer:
print("file read")
az = filer.read()
print(az)
read_file = az.rstrip('/n')
data = json.loads(read_file)
#print("printing file",json.loads(read_file))
time=data["timer"]
#print(read_file)
print(time)
print("Waiting.....................")
#time.sleep(2)
final = str(val)
print(final)
read_file = read_file.replace(
time, final)
with open('/home/pi/config.json', 'w') as filer:
filer.write(read_file)
请让我知道如何解决此错误。
解决方案
尝试这个:
import json
import os
import time
val = input("Enter your value: ")
print(val)
str1 = " "
with open('/home/pi/config.json', 'r+') as filer:
print("file read")
az = filer.read()
print(az)
read_file = az.rstrip('/n')
data = json.loads(read_file)
#print("printing file",json.loads(read_file))
time=data["timer"]
#print(read_file)
print(time)
print("Waiting.....................")
#time.sleep(2)
final = str(val).split()
final = [int(i) for i in final]
print(final)
print(str(time))
read_file = read_file.replace(str(time), str(final))
print(read_file)
with open('/home/pi/config.json', 'w') as filer:
filer.write(read_file)
并将json文件更新"timer": [0,23,30]
为"timer": [0, 23, 30]
即添加空格
推荐阅读
- android - 使用 jarsigner 在 Azure 管道上签名 Android 包失败,并出现错误“请指定别名”
- path - 如何在主页上设置信息并在单击另一个按钮/链接时触发
- asp.net - asp.net Core 在 UseRouting 之后在中间件中添加响应头
- google-apps-script - 有没有办法在 Google Apps 脚本中每隔几秒调用一次自定义函数?
- sql - 在单个列中针对给定日期返回活动记录与非活动记录计数
- mysql - 在 WHERE 子句中找到重复项时返回?
- design-patterns - 微服务和耦合——相互竞争的设计原则
- c# - Newtonsoft.Json 依赖项未在“dotnet publish -o”上以正确的版本发布
" - docker - Dockerfile:尝试创建 openssl 证书。没有错误,但没有创建文件
- r - sinh() 在 R 中返回 inf