首页 > 解决方案 > 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)

请让我知道如何解决此错误。

标签: pythonjson

解决方案


尝试这个:

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]即添加空格


推荐阅读