Python 'No JSON object could be decoded' 可能存在编码错误

Python 'No JSON object could be decoded' possible encoding error

我是 运行 自定义脚本,在 writing/reading 到 json 文件时遇到问题。 它在几周前工作,但突然它不再工作了,我不确定为什么。 我之前使用 with open() 现在将其更改为 io.open() 以强制 编码 但没有运气..

try:
    t_name= None
    if os.path.isdir(directory) and path.isfile(filepath):

        t_name= EXEC_PARAMS.event_args.GetTransactionNames()[0]
        if t_name!= None:

            with io.open(filepath, "r", encoding='utf8') as json_in:

                myObject = json_in.read()
                u = myObject.decode('utf-8-sig')
                myObject = u.encode('utf-8')
                print(json_in.encoding)

                data = json.load(json_in)
                if t_namein data.keys():
                    data[t_name] += 1
                else:
                    data[t_name] = 1

            with io.open(filepath, 'wb', encoding='utf8') as json_out:
                json.dump(data, json_out, ensure_ascii=False)

except Exception, e:
    print(e.message)
    pass

输出为:

utf8 
No JSON object could be decoded

知道这里出了什么问题吗?

编辑:

错误在 json.load() 行。

Script Executor Traceback:
IronPython.Runtime.Exceptions.ValueErrorException: No JSON object could be decoded
 at Microsoft.Scripting.Interpreter.ThrowInstruction.Run(InterpretedFrame frame)
 at Microsoft.Scripting.Interpreter.Interpreter.HandleException(InterpretedFrame frame, Exception exception)
 at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
 at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
 at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
 at PyRevitLabs.PyRevit.Runtime.IronPythonEngine.Execute(ScriptRuntime& runtime)

在这一行中您读取文件,将文件指针前进到文件末尾:

myObject = json_in.read()

然后在这一行中,您再次读取文件

data = json.load(json_in)

但是现在文件指针在文件末尾,所以没有数据可读,所以Python报告No JSON object could be decoded

如果要读取文件两次,则需要在第二次尝试读取之前将文件指针重置为文件开头,如下所示:

json_in.seek(0)

然而,在问题的代码中,第二次阅读似乎没有必要;相反,您可以删除第二次读取并从 myObject:

加载数据
myObject = json_in.read()
u = myObject.decode('utf-8-sig')
myObject = u.encode('utf-8')
print(json_in.encoding)

# Load the data we have already read
data = json.loads(myObject)

if t_namein data.keys():
    data[t_name] += 1
else:
    data[t_name] = 1

或者直接从文件加载 json,跳过不必要的解码尝试(以 'r' 模式打开的文件中的数据将是一个 unicode 实例)。

with io.open(filepath, "r", encoding='utf8') as json_in:

    data = json.load(json_in)
    if t_namein data.keys():
        data[t_name] += 1
    else:
        data[t_name] = 1